Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count the number of items in a php associative array

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?

like image 333
Navdeep Avatar asked May 15 '12 15:05

Navdeep


3 Answers

$count = 0;
foreach ($array as $key=>$value) {
    if ($value ['item'] == 'Banana Cream Cheesecake') {
        $count++;
    }
}
echo $count;
like image 198
Jeroen Avatar answered Sep 22 '22 12:09

Jeroen


array_count_values(array_map(function($foo){return $foo['item'];}, $arr));
like image 23
steve Avatar answered Sep 21 '22 12:09

steve


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'];
like image 25
mpratt Avatar answered Sep 20 '22 12:09

mpratt