我有以下数组;

Array
(
    [2019-11-01] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [category] => cat1
                )
        [1] => stdClass Object
            (
                [id] => 2
                [category] => cat2
            )

        [2] => stdClass Object
            (
                [id] => 3
                [category] => cat1
            )

        [3] => stdClass Object
            (
                [id] => 4
                [category] => cat2
            )

        [4] => stdClass Object
            (
                [id] => 5
                [category] => cat1
            )

        [5] => stdClass Object
            (
                [id] => 6
                [category] => cat2
            )

    )

[2019-11-03] => Array
    (
        [0] => stdClass Object
            (
                [id] => 7
                [category] => cat1
            )

    )

)

我想找出类别的统计数据。

喜欢:

cat1 数量:4

cat2 数量:3

我可以使用下面使用的代码获得 cat1 的结果:
$cat1count = 0;

foreach ($myArray as $date => $content) {

    foreach ($content as $value) {
        if ($value->category == "cat1") {
            $cat1count++;
        }
    }
}

echo "Cat1 count:".$cat1count;
#Outputs: Cat1 count:4

但我想知道,

如何在不硬编码类别名称的情况下获得相同的结果,就像我在“cat1”上面所做的那样

对于每个类别(cat1,cat2)?

提前致谢!

最佳答案

您可以使用 array_column() 的组合从数据中提取类别值,然后使用 array_count_values() 计算每个日期中有多少。

此代码仅显示日期,然后显示值的计数...

foreach ( $myArray as $date => $content) {
    $categories = array_column($content, "category");
    echo $date.PHP_EOL;
    print_r(array_count_values($categories));
}

如果您想要所有日期的总计,那么只需将它们添加到总计数组中...
$totals = [];
foreach ( $myArray as $date => $content) {
    $categories = array_column($content, "category");
    foreach (array_count_values($categories) as $category => $count )  {
        $totals[$category] = ($totals[$category]??0) + $count;
    }
}

关于php - 如何计算属于某个键的多维数组值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60240028/

10-13 05:34