3

I can't find an answer to this anywhere.

foreach ($multiarr as $array) {
   foreach ($array as $key=>$val) {
      $newarray[$key] = $val;
   }
}

say $key has duplicate names, so when I am trying to push into $newarray it actually looks like this:

$newarray['Fruit'] = 'Apples';
$newarray['Fruit'] = 'Bananas';
$newarray['Fruit'] = 'Oranges';

The problem is, the above example just replaces the old value, instead of pushing into it.

Is it possible to push values like this?

Norse
  • 5,674
  • 16
  • 50
  • 86

2 Answers2

13

Yes, notice the new pair of square brackets:

foreach ($multiarr as $array) {
   foreach ($array as $key=>$val) {
      $newarray[$key][] = $val;
   }
}

You may also use array_push(), introducing a bit of overhead, but I'd stick with the shorthand most of the time.

moonwave99
  • 21,957
  • 3
  • 43
  • 64
0

I'll offer an alternative to moonwave99's answer and explain how it is subtly different.

The following technique unpacks the indexed array of associative arrays and serves each subarray as a separate parameter to array_merge_recursive() which performs the merging "magic".

Code: (Demo)

$multiarr = [
    ['Fruit' => 'Apples'],
    ['Fruit' => 'Bananas'],
    ['Fruit' => 'Oranges'],
    ['Veg'   => 'Carrot'],
    //['Veg'   => 'Leek'],
];

var_export(
    array_merge_recursive(...$multiarr)
);

As you recursively merge, if there is only one value for a respective key, then a subarray is not used, if there are multiple values for a key, then a subarray is used.

See this action by uncommenting the Leek element.


p.s. If you know that you are only targetting a single column of data and you know the key that you are targetting, then array_column() would be a wise choice.

Code: (Demo)

var_export(
    ['Fruit' => array_column($multiarr, 'Fruit')]
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136