Skip to content
Advertisement

Combine/Merge arrays that have the same keys PHP

I have an array that has some keys that are repeating multiple times. Would like to combine them so that I can have them in one array, within the same array. I have an array of this type;

Array
(
    [Shoes] => Array
        (
            [POLO] => Array
                (
                    [0] => Size5
                )

        )

)
Array
(
    [Shoes] => Array
        (
            [FUBU] => Array
                (
                    [0] => size6
                )

        )

)
Array
(
    [Bag] => Array
        (
            [HPBAG] => Array
                (
                    [0] => Black
                )

        )

)
Array
(
    [Bag] => Array
        (
            [HPBAG] => Array
                (
                    [0] => White
                )

        )

)

I would like an output of the following kind;

Array
    (
        [Shoes] => Array
            (
                [POLO] => Array
                    (
                        [0] => size5
                    )
                [FUBU] => Array
                    (
                        [0] => size6
                    )
    
            )

        [Bag] => Array
            (
                [HPBAG] => Array
                    (
                        [0] => Black
                        [1] => White
                    )
    
            )
    
    )

I have tried array_merge, array_merge_recursive but all are not working.

foreach ($county as $value) { print_r(array_merge($value)); } //$value contains the array 

foreach ($county as $value) { print_r(array_merge_recursive($value)); } //$value contains the array 

Kindly assist if you have an idea on how to solve this in PHP.

Advertisement

Answer

You could do it with a few nested array_walk() calls:

$arr=array(array("Shoes" => array("POLO" => array("Size5"))),
      array("Shoes" => array("FUBU" => array("size6"))),
      array("Bag" => array("HPBAG" => array("Black"))),
      array("Bag" => array("HPBAG" => array("White"))));

$res=[];
array_walk($arr,function($a) use (&$res){ 
    array_walk($a, function($ar,$type) use (&$res){
        array_walk($ar, function ($arr,$brand) use (&$res,$type){
            $res[$type][$brand]=array_merge($res[$type][$brand]??[],$arr);
        });
    });
});

print_r($res);

See the demo here: https://rextester.com/RFLQ18142

It produces this result:

Array
(
    [Shoes] => Array
        (
            [POLO] => Array
                (
                    [0] => Size5
                )

            [FUBU] => Array
                (
                    [0] => size6
                )

        )

    [Bag] => Array
        (
            [HPBAG] => Array
                (
                    [0] => Black
                    [1] => White
                )

        )

)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement