Tyler Nichol Tyler Nichol - 7 months ago 6
PHP Question

merge recursive on inner arrays of multidimensional array php

I have a multidimensional array that looks like such:

Array
(
[0] => Array
(
[email] => email1@gmail.com
[added] => style-narcotics
)

[1] => Array
(
[email] => email1@gmail.com
[added] => style-edm
)

[2] => Array
(
[email] => email2@gmail.com
[added] => style-codeine
)

[3] => Array
(
[email] => email2@gmail.com
[added] => style-food
)
)


I want to merge all the inner arrays combining the "added" key like such:

Array
(
[0] => Array
(
[email] => email1@gmail.com
[added] => array(
[0]=>style-narcotics
[1]=>style-edm
)
)



[1] => Array
(
[email] => email2@gmail.com
[added] => array(
[0]=>style-codeine
[1]=>style-food
)

)


I have tried merge array recursive in different forms and call_user_func but it doesnt cut it. Any advice? Thanks!

Answer

I would call it "grouping", but not "merging".
Use the following approach with array_walk and array_values functions:

$grouped = [];
// $arr is your initial array
array_walk($arr, function($v) use (&$grouped){
    if (array_key_exists($v["email"], $grouped)) {
        $grouped[$v["email"]]["added"][] = $v["added"];
    } else {
        $v["added"] = [$v["added"]];
        $grouped[$v["email"]] = $v;
    }
});

print_r(array_values($grouped));

The output:

Array
(
    [0] => Array
        (
            [email] => email1@gmail.com
            [added] => Array
                (
                    [0] => style-narcotics
                    [1] => style-edm
                )

        )

    [1] => Array
        (
            [email] => email2@gmail.com
            [added] => Array
                (
                    [0] => style-codeine
                    [1] => style-food
                )
        )
)