PHP ARRAY - 结合或分组?

时间:2016-11-17 22:59:43

标签: php arrays

我有以下数组:

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
        )

)

我想将重复日合并在一起,同时将2个值([1] + [1]和[2] + [2])加在一起。

例如,星期五是重复的,所以会返回:             [0] =>星期五             [1] => 6791             [2] => 2

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

迭代数组,将值添加到另一个数组(下面为$combined),将日期作为键。

$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));

输出:

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
        )
)

答案 1 :(得分:0)

这样的事情应该有效。

$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);

如果你需要钥匙,只需再次对它们进行整理。

$sorted = array();

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

$days = $sorted;