1

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this throws out: unexpected T_FUNCTION, expecting ')'
@danyo If your php version is < 5.3, then you can't use anonymous function. You could either create a function or just use a loop to collect the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.