AnalogKidult
AnalogKidult

Reputation: 3

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
          )

Upvotes: -2

Views: 43

Answers (2)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

Or you can simply use array_walk as

$result = [];
array_walk($array,function($v,$k)use(&$result){$result[$v[0]][] = $v[1];});
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
        )

)

Upvotes: 1

mhall
mhall

Reputation: 3701

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
        )

)

Upvotes: 0

Related Questions