fightstarr20
fightstarr20

Reputation: 12568

PHP combine 2 arrays into a third

Given 2 arrays in PHP that look like this...

Array
(
    [item1] => Array
        (
            [myValues] => Array
                (
                    [1] => 5
                    [2] => 1
                )

        )

    [item2] => Array
        (
            [myValues] => Array
                (
                    [1] => 5
                    [2] => 1
                )

        )

)

Array
(
    [item1] => Array
        (
            [1] => 2
        )

    [item2] => Array
        (
            [1] => 5
            [2] => 1
        )

)

array1
array ( 'item1' => array ( 'myValues' => array ( 1 => 5, 2 => 1, ), ), 'item2' => array ( 'myValues' => array ( 1 => 5, 2 => 1, ), ), )

What is the best way to combine them into an array that looks like this...

Array
(
    [item1] => Array
        (
            [myValues] => Array
                (
                    [1] => 5
                    [2] => 1
                )
            [myValues2] => Array
                (
                    [1] => 2
                )

        )

    [item2] => Array
        (
            [myValues] => Array
                (
                    [1] => 5
                    [2] => 1
                )
            [myValues2] => Array
                (
                    [1] => 5
                    [2] => 1
                )

        )

)

array2
array ( 'item1' => array ( 1 => 2, ), 'item2' => array ( 1 => 5, 2 => 1, ), )

I have no control over the output so I am thinking my best approach would be to loop over each array and copy the items into a fresh one.

I have tried...

print_r(array_merge($a1,$a2));

But this is not giving me the result I am looking for. Does anybody have an example?

Upvotes: 0

Views: 59

Answers (1)

mickmackusa
mickmackusa

Reputation: 47864

Push your array2 data into array1 by using the known first level key and your invented second level key.

Code: (Demo)

$array1 = array ( 'item1' => array ( 'myValues' => array ( 1 => 5, 2 => 1, ), ), 'item2' => array ( 'myValues' => array ( 1 => 5, 2 => 1, ), ), );
$array2 = array ( 'item1' => array ( 1 => 2, ), 'item2' => array ( 1 => 5, 2 => 1, ), );

foreach ($array2 as $key => $subarray) {
    $array1[$key]['myValues2'] = $subarray;
}

var_export($array1);

Output:

array (
  'item1' => 
  array (
    'myValues' => 
    array (
      1 => 5,
      2 => 1,
    ),
    'myValues2' => 
    array (
      1 => 2,
    ),
  ),
  'item2' => 
  array (
    'myValues' => 
    array (
      1 => 5,
      2 => 1,
    ),
    'myValues2' => 
    array (
      1 => 5,
      2 => 1,
    ),
  ),
)

Upvotes: 2

Related Questions