Skip to content
Advertisement

Group associative row data based on shared column value

I have a multidimensional array like:

Array
(
    [0] => Array
        (
            [division] => Mymensingh
            [A] => 1
        )    
    [1] => Array
        (
            [division] => Dhaka
            [A] => 5
        )
    [2] => Array
        (
            [division] => Mymensingh
            [B] => 2
            [C] => 5
        )
)

I need to find the rows with matching division values and merge them in one array.

From this array, I want the output as:

Array
    (
        [0] => Array
            (
                [division] => Mymensingh
                [A] => 1
                [B] => 2
                [C] => 5
            )    
        [1] => Array
            (
                [division] => Dhaka
                [A] => 5
            )
    )

Keys in the subarrays can be different and the subarrays may have a differing number of elements.

Advertisement

Answer

I think it’s relatively simple to just iterate through the array and continuously merge the entries separated by “division”:

function mergeByDiscriminator($input, $discriminator = 'division') {
    $result = [];

    foreach ($input as $array) {
        $key = $array[$discriminator];
        $result[$key] = array_merge(
            array_key_exists($key, $result) ? $result[$key] : [],
            $array
        );
    }

    return array_values($result);
}

$result = mergeByDiscriminator($input); // $input is your array
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement