user2122151 user2122151 - 3 months ago 15
PHP Question

Array Merge Dynamic Multidimensional Array by Key

This is my multidimensional array example. This is generated through a form so this is a dynamic array, so there may be more than 3 entries.



Array
(
[0] => Array
(
[itemNo] => 1
[desc] => Array
(
[0] => Array
(
[serialNo] => 1
[name] => a
)

[1] => Array
(
[serialNo] => 2
[name] => b
)

)

[quantity] => 2
)

[1] => Array
(
[itemNo] => 2
[desc] => Array
(
[0] => Array
(
[serialNo] => 1
[name] => a1
)

)

[quantity] => 1
)

[2] => Array
(
[itemNo] => 1
[desc] => Array
(
[0] => Array
(
[serialNo] => 3
[name] => c
)

)

[quantity] => 1
)
)





I want to merge these arrays by key [itemNo]. In this example Array[0] and Array[2] have the same key '1'.

This result I want is...



Array
(
[0] => Array
(
[itemNo] => 1
[desc] => Array
(
[0] => Array
(
[serialNo] => 1
[name] => a
)

[1] => Array
(
[serialNo] => 2
[name] => b
)

[2] => Array
(
[serialNo] => 3
[name] => c
)

)

[quantity] => 3
)

[1] => Array
(
[itemNo] => 2
[desc] => Array
(
[0] => Array
(
[serialNo] => 1
[name] => a1
)

)

[quantity] => 1
)
)




Answer

As always for grouping problems like these, use itemNo as the key in the grouped array you're trying to generate.

foreach ($your_array as $x) {
    $id = $x['itemNo'];  // set the key


    if (isset($grouped[$id])) {

        // increment if that id is already set
        $grouped[$id]['desc'] = array_merge($grouped[$id]['desc'], $x['desc']);
        $grouped[$id]['quantity'] += $x['quantity'];
    } else {

        // add the entire entry if not
        $grouped[$id] = $x;
    }   
}