user381800
user381800

Reputation:

How to combine/merge an multidimension array that has same keys in PHP?

So I have this array which the vardump looks like this:

array (size=4)
  0 => 
    array (size=1)
      'field_4' => 
        array (size=1)
          0 => string 'item-1' (length=6)
  1 => 
    array (size=1)
      'field_4' => 
        array (size=1)
          0 => string 'info-1' (length=6)
  2 => 
    array (size=1)
      'field_5' => 
        array (size=1)
          0 => string 'item-2' (length=6)
  3 => 
    array (size=1)
      'field_5' => 
        array (size=1)
          0 => string 'info-2' (length=6)

So I am trying to combine the array with the same key for example 'field_4' would be merge/combined into an array that has 2 items "item-1" and "info-1".

So the end result I would like is this:

array (size=2)
  0 => 
    array (size=1)
      'field_4' => 
        array (size=2)
          0 => string 'item-1' (length=6)
          1 => string 'info-1' (length=6)
  1 => 
    array (size=1)
      'field_5' => 
        array (size=1)
          0 => string 'item-2' (length=6)
          1 => string 'info-2' (lenght=6)

So is there a PHP convenience function to handle this or do I have to rebuild the array?

Thanks for looking.

Upvotes: 2

Views: 105

Answers (1)

Cal
Cal

Reputation: 7157

Just iterate over the input array, building the merged array:

$merged = array();
foreach ($input as $a)
    foreach ($a as $k => $v)
        foreach ($v as $v2)
            $merged[$k][] = $v2;

And then flatten it into your weird required output:

$flattened = array();
foreach ($merged as $k => $v)
    $flattened[] = array($k => $v);

Input:

$input = array(
    array('field_4' => array('item-1')),
    array('field_4' => array('info-1')),
    array('field_5' => array('item-2')),
    array('field_5' => array('info-2')),
);

Output:

array(
    array('field_4' => array('item-1', 'info-1')),
    array('field_5' => array('item-2', 'info-2')),
)

When dumping output, print_r or var_export make for a much more readable example than var_dump

Upvotes: 1

Related Questions