I have an array like this
Array
(
[0] => Array
(
[label] => A
[uid] => 429
[country_id] => 3
[date] => 2015-02-11 13:55:34
[DiffDate] => 20
)
[1] => Array
(
[label] => A
[uid] => 429
[country_id] => 2
[date] => 2015-02-11 13:55:34
[DiffDate] => 20
)
...... and so on
)
Now I have to calculate number of occurrences of country records example
country 1 has total 10 occurrence
country 2 has total 20 occurrence
I need help as there are lot of arrays created also I am getting country id as different array
thanks in advance
There are a number of ways to tackle this. I like the following approach:
Restructure the array, so it's just a list of countries using array_column
$countries = array_column($array, 'country_id');
or for PHP 5.4
$countries = array_map(function($item) {
return $item['country_id'];
}, $array);
Use array_count_values
to get the number of occurrences for each country
$occurrences = array_count_values($countries);
If you need to do a check before adding the country to the $countries
array, you're better of with a foreach
loop than with array_map
.
$countries = []
foreach ($array as $item) {
if ($item['DiffDate'] >= 3) $countries[] = $item['country_id'];
}