2d数组 - 按值分组并总结相同的键值

时间:2014-07-22 13:33:32

标签: php arrays multidimensional-array

您好,感谢您花时间查看我的问题。

我目前的问题是,我有以下数组($topics_percentage):

Array
(
    [0] => Array
        (
            [id] => 8989
            [cat] => Category 1
            [completed] => 0
        )

    [1] => Array
        (
            [id] => 8919
            [cat] => Category 2
            [completed] => 1
        )

    [2] => Array
        (
            [id] => 8913
            [cat] => Category 2
            [completed] => 1
        )

    [3] => Array
        (
            [id] => 8947
            [cat] => Category 1
            [completed] => 1
        )

    [4] => Array
        (
            [id] => 8949
            [cat] => Category 3
            [completed] => 1
        )

)

我需要得到的是类似下面的例子:

Array
(
    [Category 1] => Array
        (
            [noncompleted] => 1
            [completed] => 1
        )

    [Category 2] => Array
        (
            [completed] => 2
        )

    [Category 3] => Array
        (
            [completed] => 1
        )

)


到目前为止我尝试过的是:

$class_array = [];

foreach ($topics_percentage as $v) {

    $complete = $v['completed'];

    $class_array[$v['cat']][] =
        ($complete == 0 ? 'noncompleted' : 'completed');
}

返回以下内容:

Array
(
    [Category 1] => Array
        (
            [0] => noncompleted
            [1] => completed
        )

    [Category 2] => Array
        (
            [0] => completed
            [1] => completed
        )

    [Category 3] => Array
        (
            [0] => completed
        )

)

在数组方面我很弱,无法弄清楚逻辑。

提前致谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

$values = array_unique(array_map(
    function ($v) { return $v['cat']; },
    $array
));

$result = array();
foreach ($values as $val) {
    $flt = array_filter($array, function ($v) use ($val) {
        return $v['cat'] == $val;
    });
    $cnt = count(array_filter($array, function ($v) use ($val) {
        return $v['completed'];
    }));
    $result[$val] = array(
        'completed' => $cnt,
        'noncompleted' => count($flt) - $cnt
    );
}

答案 1 :(得分:0)

试试这个:

    foreach ($topics_percentage as $v) {

        $complete = $v['completed'];

        if ($complete == 1) {
            $class_array[$v['cat']]['completed']++;
        } else {
            $class_array[$v['cat']]['uncompleted']++;
        }
    }

当然,您应该在计算值之前预先初始化数组,但基本思路是使用数组单元作为数值来添加或减去。