Search code examples
phphtmlarraysexplode

PHP: map array with explode keys involved


after trying to solve this with multiple foreach loops I still cant figure out how to map $arr to $arr_mapped

I need to explode the keys of $arr to get an element with up to three new keys to create $arr_mapped


<?php

$arr = [
  'abc:quantity' => 1,
  'abc:variant' => 'blue',
  'xyz:quantity' => 2,
  'foo:quantity' => null
];

$arr_mapped = [
  [
    'id' => 'abc',
    'quantity' => 1,
    'variant' => 'blue'
  ],
  [
    'id' => 'xyz',
    'quantity' => 2,
  ]
];

background: I want to let a user bulk add predefined shopping items in a <form> Its a custom PHP Shop.


<form>

<input name="abc:quantity" value="1">
<input name="abc:variant" value="blue">
<input name="xyz:quantity" value="2">
<input name="foo:quantity" value="">

<button>Submit</button>
</form>

thanks for any suggestions


Solution

  • I think this will produce the output you want based on the input you provided in your example (which doesn't seem to match the output in your example):

    $arr = [
      'abc:quantity' => 1,
      'abc:variant' => 'blue',
      'xyz:quantity' => 2,
      'foo:quantity' => null
    ];
    
    $arr_mapped = array_values(array_reduce(array_keys($arr), function($map, $key) use ($arr) {
        [$id,$field] = explode(':', $key);
        $map[$id]['id'] = $id;
        $map[$id][$field] = $arr[$key];
        return $map;
    }, []));
    

    result:

    [
      [
        'id' => 'abc',
        'quantity' => 1,
        'variant' => 'blue'
      ],
      [
        'id' => 'xyz',
        'quantity' => 1,
      ],
      [
        'id' => 'foo',
        'quantity' => null,
      ]
    ];