Search code examples
phparraysmultidimensional-arraygroupingsub-array

Group 2d array data by one column and fills a subarray with values from another column per group


I have array like:

Array
(
    [0] => Array
        (
            [0] => Product_1
            [1] => Gold
        )

    [1] => Array
        (
            [0] => Product_1
            [1] => Silver
        )

    [2] => Array
        (
            [0] => Product_1
            [1] => Black
        )

    [3] => Array
        (
            [0] => Product_1
            [1] => Red
        )

    [4] => Array
        (
            [0] => Product_2
            [1] => Silver
        )

    [5] => Array
        (
            [0] => Product_2
            [1] => Gold
        )

    [6] => Array
        (
            [0] => Product_2
            [1] => Black
        )

How can I sort this array into

[Product_1] => Array
          ( 
            [0] Silver
            [1] Black
            [2] Red
          )
[Product_2] => Array
          (
            [0] Silver
            [1] Gold
            [2] Black
          )

Solution

  • Just loop through your $array and push each color value to a $result array having the product name as the key.

    $array = [
        ['Product_1', 'Gold'],
        ['Product_1', 'Silver'],
        ['Product_1', 'Black'],
        ['Product_1', 'Red'],
        ['Product_2', 'Silver'],
        ['Product_2', 'Gold'],
        ['Product_2', 'Black'],
    ];
    
    $result = [];
    
    foreach ($array as $values) {
        list ($product, $color) = $values;
        $result[$product][] = $color;
    }
    
    print_r($result);
    

    Output:

    Array
    (
        [Product_1] => Array
            (
                [0] => Gold
                [1] => Silver
                [2] => Black
                [3] => Red
            )
    
        [Product_2] => Array
            (
                [0] => Silver
                [1] => Gold
                [2] => Black
            )
    
    )