Question

I would like to count the occurances of data in a associative array i have. Here is the output of my array:

Array ( [0] => Array ( [url] => http://test.com [date] => 14-04-2014 [time] => 16:06:09 ) [1] => Array ( [url] => Direct [date] => 14-04-2014 [time] => 16:06:37 ) [2] => Array ( [url] => http://test.com [date] => 15-04-2014 [time] => 08:10:43 ) [3] => Array ( [url] => http://test.com [date] => 15-04-2014 [time] => 08:50:02 ) [4] => Array ( [url] => http://test.com [date] => 15-04-2014 [time] => 08:50:06 ) [5] => Array ( [url] => http://test.com [date] => 15-04-2014 [time] => 08:50:09 ) )

I then loop through the results like this:

foreach ($refs as $key => $va){

echo $va['date'];   

}

I would like to count the dates that are the same.

So the above would produce:

14-04-2014 = 2
15-04-2014 = 3

What is the best approach to do this? I have tried using array_count_values but cant seem to get this to work with an associative array. I get the following error:

Warning: array_count_values() [FUNCTION.ARRAY-COUNT-VALUES]: Can only count STRING and INTEGER values!
Was it helpful?

Solution

You could use array_map to convert the array first.

$result = array_count_values(array_map(function ($var) {
  return $var['date'];
}, $refs));

For php < 5.3:

$dates = array();

foreach ($refs as $ref) {
  $dates[] = $ref['date'];
}

$result = array_count_values($dates);

You could also not use array_count_values and do the counting in the loop directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top