PHP ARRAY - 结合或分组? [重复]

This question already has an answer here:

I have the following array:

Array
(
    [0] => Array
        (
            [0] => Monday
            [1] => 0
            [2] => 1
        )

    [1] => Array
        (
            [0] => Friday
            [1] => 4717
            [2] => 1
        )

    [2] => Array
        (
            [0] => Friday
            [1] => 2074
            [2] => 1
        )

    [3] => Array
        (
            [0] => Thursday
            [1] => 1520
            [2] => 1
        )

)

I would like to combine duplicate days together while also adding the 2 values ([1]+[1] and [2]+[2]) together.

For example, Friday is a duplicate so it would return: [0] => Friday [1] => 6791 [2] => 2

Any ideas?

</div>

Iterate the array, adding the values to another array ($combined below) using the day as key.

$array = [ [ 'Monday',      0, 1 ],
           [ 'Friday',   4717, 1 ],
           [ 'Friday',   2074, 1 ],
           [ 'Thursday', 1520, 1 ] ];

$combined = [];

foreach ($array as $value) {
    $day = $value[0];
    if (!array_key_exists($day, $combined)) {
        # Does not exist, create in resulting array
        $combined[$day] = $value;
    }
    else {
        # Exists - add to values
        $combined[$day][1] += $value[1];
        $combined[$day][2] += $value[2];
    }
}
print_r(array_values($combined));

Output:

Array
(
    [0] => Array
        (
            [0] => Monday
            [1] => 0
            [2] => 1
        )

    [1] => Array
        (
            [0] => Friday
            [1] => 6791
            [2] => 2
        )

    [2] => Array
        (
            [0] => Thursday
            [1] => 1520
            [2] => 1
        )
)

Something like this should work.

$sorted = array();

foreach ($days as $day) {
    $sorted[ $day[0] ][ 0 ] = $day [ 0 ];
    $sorted[ $day[0] ][ 1 ] += $day [ 1 ];
    $sorted[ $day[0] ][ 2 ] += $day [ 2 ];
}

$days = $sorted;

print_r($days);

If you need the keys back, simply sort over them again.

$sorted = array();

foreach ($days as $day) {
    $sorted[] = $day;
}

$days = $sorted;