-1

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

1
  • Where are you getting the array from? Also what have you tried? Commented Oct 2, 2017 at 13:17

2 Answers 2

4

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

Please dont post code-only answers. Add a bit of explanaition why this works and how.
Thank you I didnt realise these were methods, I guess I wasnt looking properly at the documentation
1

Supposing your array is like so :

<?php 
$dates = ['02-10-2017', '02-10-2017', '01-09-2017'];
?> 

You can use array_count_values like this :

<?php
    print_r(array_count_values($dates));
?>

The output will be something like :

Array
(
    [02-10-2017] => 2
    [01-09-2017] => 1
)

If you want the keys to be the count, you can use the array_flip function.

Comments

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.