Search code examples
phparraysmergekeysub-array

How to merge array by key values which are repeating


I have an array like this what i want is to sub array converts into unique key sub array with multiple unique keys. I have tried array_merge_recursive function which is not working because i have multiple arrays in loop and the function works with 2 or 3 arrays.

Array
(
    [0] => Array
        (
            [fromWho] => abc@email.se
        )

    [1] => Array
        (
            [tid] => 2013-05-05 23:35
        )

    [2] => Array
        (
            [answer] => Company
        )

    [3] => Array
        (
            [name] => message
        )

    [4] => Array
        (
            [label] => Message
        )

    [5] => Array
        (
            [fromWho] => bcd@email.se
        )

    [6] => Array
        (
            [tid] => 2013-05-05 23:35
        )

    [7] => Array
        (
            [answer] => Star Company
        )

    [8] => Array
        (
            [name] => name
        )

    [9] => Array
        (
            [label] => Name
        )
)

I want the array like this array keys order doesn't matter:

Array
(
    [0] => Array
        (
            [label] => Message
            [name] => message
            [answer] => Company
            [tid] => 2013-05-05 23:35
            [fromWho] => abc@email.se
        )

    [0] => Array
        (
            [label] => Name
            [name] => name
            [answer] => Star Company
            [tid] => 2013-05-05 23:35
            [fromWho] => bcd@email.se
        )
)

Solution

  • Use array_chunk() to group the array into chunks of 5 elements. Then you can convert each chunk into an associative array.

    $chunks = array_chunk($data, 5);
    $result = array_map(function($chunk) {
        $arr = [];
        foreach ($chunk as $entry) {
            foreach ($entry as $key => $val) {
                $arr[$key] = $val;
            }
        }
        return $arr;
    }, $chunks);