Search code examples
phparraysmultidimensional-arraymappingmerging-data

Convert a flat indexed array and a flat associative array into a 2d array with predefined second level keys


I have two arrays. One is a list of colors, the second is an associative array of key value pairs. My objective is to take the key value pairs from the associative array and make them a sub-array of each item in the colors array. Searching SO has gotten me various adjacent issues, but not the one I'm having specifically. Here are two example arrays, and then $final is what I want to achieve:

$colors = ['#eea845', '#64A0B4', '#003c50', '#FF5568', '#eee', '#5cb85c', '#5bc0de', '#f0ad4e', '#d9534f'];

$test = [
  'key1' => 'val1',
  'key2' => 'val2',
  'key3' => 'val3',
  'key4' => 'val4',
  'key5' => 'val5',
  'key6' => 'val6',
  'key7' => 'val7',
  'key8' => 'val8',
  'key9' => 'val9',
];

$final = [
   '#eea845' => [
      'name' => 'key1',
      'value' => 'val1',
   ],
   '#64A0B4' => [
      'name' => 'key2',
      'value' => 'val2',
   ],
   etc.....
]

I've been looking at array_walk, array_map, and trying to figure out how to combine for and foreach loops.

I looked at the answer given here (Append one array values as key value pair to another array php), but I'm not sure how to use it on an already existing array and be able to get the index of each.

For example, that solution uses:

array_walk($array1, function(&$v, $k) use($array2) {
    $v['date'] = $array2[$k];
});

but I need to have the values from $array2 be added to already existing items in $array1, and while I tried doing function($i, $v, $k) with $i being the index inside $array1, that didn't work, $i being undefined.

I'm stumped and not sure where to look next. How would you synchronously iterate the two arrays to build a structure like this:

return $colors[$i] => 
  [
   'name' => $test[$key], 
   'value' => $test[$name] 
  ]

For context, I am using this to get values to input into a Twig template, and this looks like the best way to do it for that half of the problem.


Solution

  • There are several ways to do it. One way is to use foreach on the associative array, so you get key and value in separate variables, and to use next() to get the corresponding value from the first (indexed) array:

    foreach ($test as $key => $value) {
        $final[current($colors)] = ["name" => $key, "value" => $value];
        next($colors);
    }
    

    In the rare event you had already used next() on $colors, you'll have to call reset($colors) before starting this loop.