Reputation: 115
I am trying to get the count of key data and sum them up and show. I need to count all the key data in a php array and show the output as below i tried but was not able to get all the array count.
Output:
chromi: 7
detruch: 6
detroy: 4
Find the array picture below, this is how i am getting array data
Upvotes: 0
Views: 82
Reputation: 11642
Better way will be to get array of values and use array-count-values:
$array = [
['someKey' => 'Value 1'],
['someKey1' => 'Value 1'],
['someKey2' => 'Value 2'],
['someKey3' => 'Value 3'],
];
$arr = array_map(function ($e) {return reset($e);},$array);
print_r(array_count_values($arr));
Output will be:
Array
(
[Value 1] => 2
[Value 2] => 1
[Value 3] => 1
)
I just improve @Qirel answer. This version can support multi-value to count. Live demo: 3v4l
Upvotes: 2
Reputation: 26450
Loop the array, pick the first value using reset()
, and count that index of the $result
array.
$array = [
['someKey' => 'Value 1'],
['someKey1' => 'Value 1'],
['someKey2' => 'Value 2'],
['someKey3' => 'Value 3'],
];
$result = [];
foreach ($array as $v) {
$value = reset($v);
if (!isset($result[$value]))
$result[$value] = 0;
$result[$value] += 1;
}
print_r($result);
Upvotes: 1
Reputation: 3724
First flip thekey with value and then loop the array to incrment the counters :
Try this snippet :
$chromi = 0 ;
$detruch = 0 ;
$detroy = 0;
$data = array_flip($data);
foreach($data as $key=>$value){
if($key=='chromi'){
$chromi++;
}
else if ($key=='chromi'){
$chromi++
}
else if ($key=='detroy'){
$detroy++
}
}
Upvotes: 0