user3074140 user3074140 - 2 years ago 167
PHP Question

PHP Iterate over array and get count for each item

I have an array containing dates, I want to iterate over the array to get a count for how many times a date appears. I want the data to be displayed in a chart so the result needs to be in the form

data:[
[count, date],
[count, date],
[count, date]
]


so that the count for each date is in an array with it.

I was having some difficulty trying to find a good way to do this, or if there was a method that I may have overlooked

Answer Source

Make use of array_column(), and array_count_values():

with array_column you will get second element of each sub array, and array_count_values will give you count.

array_count_values(array_column($array, 1));

array_column — Return the values from a single column in the input array (PHP 5 >= 5.5.0, PHP 7)

array_count_values — Counts all the values of an array (PHP 4, PHP 5, PHP 7)

Test Results, for array specified like below, as you requested

akshay@db-3325:/tmp$ cat test.php 
<?php

    $array = [
        [1, '02-10-2017'],
        [2, '02-10-2017'],
        [3, '04-10-2017'],
        [4, '10-10-2017']
    ];

    print_r(array_count_values(array_column($array, 1)));
?>

akshay@db-3325:/tmp$ php test.php 
Array
(
    [02-10-2017] => 2
    [04-10-2017] => 1
    [10-10-2017] => 1
)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download