Tyler Nichol
Tyler Nichol

Reputation: 655

Merge two associative multidimensional arrays

I have two arrays.

Array 1 looks like:

Array 
(

 [525133-004-TURQ/WHT-9] => Array
    (
        [classId] => 48
        [family] => Mens Shoes
        [onOrder] => 3.000
        [cost] => 45.000
        [sell] => 95.000
        [desc] => PAUL RODRIGUEZ 6, TURQ/WHT, 9
        [invStore] => 0.000
        [code] => 525133-004-TURQ/WHT-9
    )
)

Array 2 looks like:

Array
(

[525133-004-TURQ/WHT-9] => Array
    (
        [inv] => 0.000
    )
)

The result needed is:

Array 
(

 [525133-004-TURQ/WHT-9] => Array
    (
        [classId] => 48
        [family] => Mens Shoes
        [onOrder] => 3.000
        [cost] => 45.000
        [sell] => 95.000
        [desc] => PAUL RODRIGUEZ 6, TURQ/WHT, 9
        [invStore] => 0.000
        [code] => 525133-004-TURQ/WHT-9
        [inv] => 0.000
    )
)

I tried merge and it is not working.

Upvotes: 0

Views: 247

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219920

Use array_merge_recursive:

$arr1 = array(
    '525133-004-TURQ/WHT-9' => array(
        'classId' => 48,
        'family' => 'Mens Shoes',
        'onOrder' => 3.000,
        'cost' => 45.000,
        'sell' => 95.000,
        'desc' => 'PAUL RODRIGUEZ 6, TURQ/WHT, 9',
        'invStore' => 0.000,
        'code' => '525133-004-TURQ/WHT-9'
    )
);

$arr2 = array(
    '525133-004-TURQ/WHT-9' => array(
        'inv' => 0.000
    )
);

$newArray = array_merge_recursive($arr1, $arr2);

See it here in action: http://viper-7.com/jq8CgM

Upvotes: 3

Peter Kiss
Peter Kiss

Reputation: 9319

foreach ($arr1 as $key => $v1) {
    if (isset($arr2[$key])) {
        foreach ($arr2[$key] as $k => $v) {
            $arr1[$key][$k] = $v;
        }
    }
}

If i'm correct.

Upvotes: 0

Related Questions