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?

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

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')]
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.