I have an array as below.
Array
(
[0] => Array
(
[item] => Banana Cream Cheesecake
[item_id] => 3
[product] => Desserts
)
[1] => Array
(
[item] => Banana Cream Cheesecake
[item_id] => 3
[product] => Desserts
)
[2] => Array
(
[item] => Banana Cream Cheesecake
[item_id] => 3
[product] => Desserts
)
[3] => Array
(
[item] => Banana Cream Cheesecake
[item_id] => 3
[product] => Desserts
)
[4] => Array
(
[item] => Milk
[item_id] => 2
[product] => Soda
)
[5] => Array
(
[item] => Banana Cream Cheesecake
[item_id] => 3
[product] => Desserts
)
)
I want to print :-
Banana Cream Cheesecake = 5
how to do it?
$count = 0;
foreach ($array as $key=>$value) {
if ($value ['item'] == 'Banana Cream Cheesecake') {
$count++;
}
}
echo $count;
array_count_values(array_map(function($foo){return $foo['item'];}, $arr));
Given an array like this:
$arr = array(array('item' => 'Banana Cream Cheesecake',
'item_id' => 3,
'product' => 'Desserts'),
array('item' => 'Banana Cream Cheesecake',
'item_id' => 3,
'product' => 'Desserts'),
array('item' => 'Banana Cream Cheesecake',
'item_id' => 3,
'product' => 'Desserts'),
array('item' => 'Banana Cream Cheesecake',
'item_id' => 3,
'product' => 'Desserts'),
array('item' => 'Milk',
'item_id' => 2,
'product' => 'Soda'),
array('item' => 'Banana Cream Cheesecake',
'item_id' => 3,
'product' => 'Desserts'));
You could use array_count_values and get the count by its name
$counted = array_count_values(array_map(function($value){return $value['item'];}, $arr));
echo $counted['Banana Cream Cheesecake'];
Or modify the function to work with the item's id:
$counted = array_count_values(array_map(function($value){return $value['item_id'];}, $arr));
// The item_id
echo $counted['3'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With