Here I have an array. This is it:
Array ( Array (
'name' => 'bmw',
'id' => 1
), Array (
'name' => 'toyota',
'id' => 1
),Array (
'name' => 'tata',
'id' => 2
),Array (
'name' => 'bajaj',
'id' => 3
),Array (
'name' => 'kawasaki',
'id' => 3
), Array (
'name' => 'tvs',
'id' => 3
),Array (
'name' => 'mitsubishi',
'id' => 2
)
);
and what code should be next to give me result as id 1 => 2 items , id 2 => 2 items and id 3 => 3 items? I tried array_count_values()
and it doesn't work for me.
According to documentation array_count_values
works only on strings and integers. You can use it but first you should extract a column with ids. As of PHP 5.5 it's really easy, just call a function called array_column
.
$list = array ( Array (
'name' => 'bmw',
'id' => 1
), Array (
'name' => 'toyota',
'id' => 1
),Array (
'name' => 'tata',
'id' => 2
),Array (
'name' => 'bajaj',
'id' => 3
),Array (
'name' => 'kawasaki',
'id' => 3
), Array (
'name' => 'tvs',
'id' => 3
),Array (
'name' => 'mitsubishi',
'id' => 2
)
);
$results = array_count_values(array_column($list, 'id'));
Maybe there is a nicer solution, but this should work.
Assuming that your array is saved in $arr
.
$countItemsById = [];
foreach( $arr as $data ){
$countItemsById[ $data['id'] ]++;
}
This code does the following: First it is creating a new Array $countItemsById
. After that it loops trough your existing array and increases the value in the new array by 1 for the index (key)
that has the value of the id.
After that, $countItemsById
will look like this:
Array (1 => 2, 2 => 2, 3 => 3)
loop your array, to calculate the occerence for each id.
<?php
$list = array ( Array (
'name' => 'bmw',
'id' => 1
), Array (
'name' => 'toyota',
'id' => 1
),Array (
'name' => 'tata',
'id' => 2
),Array (
'name' => 'bajaj',
'id' => 3
),Array (
'name' => 'kawasaki',
'id' => 3
), Array (
'name' => 'tvs',
'id' => 3
),Array (
'name' => 'mitsubishi',
'id' => 2
)
);
$results = [];
array_walk($list, function($v) use(&$results){
$results[$v['id']]++;
});
var_dump($results);
output:
array(3) {
[1]=>
int(2)
[2]=>
int(2)
[3]=>
int(3)
}