Home » Php » php – How to count a multidimensional arrays values belongs to a certain key?

php – How to count a multidimensional arrays values belongs to a certain key?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have below array;

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
            )

    )

)

And I want to found out statistics of categories.

like:

cat1 count: 4

cat2 count: 3

I am able to get the result for cat1 with the code I use below:

$cat1count = 0;

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

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

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

But I’m wondering,

how to get same results without hardcoding the category name as I did above “cat1”

and for each category (cat1,cat2)?

Thanks in advance!

How to&Answers:

You can use a combination of array_column() to extract the category values from the data and then use array_count_values() to count how many there are in each date.

This code just displays the date and then the counts of the values…

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

If you want totals across all dates, then just add them to a totals array…

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