CodexVarg
CodexVarg

Reputation: 510

how to count specific values in php array

Hi i have array like this:

0 => 
    array (size=6)
      'id' => string '55' (length=2)
      'uid' => string '1' (length=1)
      'item_id' => string '5' (length=1)
      'item_name' => string 'dfgdfg' (length=6)
      'price' => string '14.91' (length=5)
      'time' => string '1373975023' (length=10)
  1 => 
    array (size=6)
      'id' => string '59' (length=2)
      'uid' => string '1' (length=1)
      'item_id' => string '5' (length=1)
      'item_name' => string 'dfgdfg' (length=6)
      'price' => string '14.91' (length=5)
      'time' => string '1373978756' (length=10)
  2 => 
    array (size=6)
      'id' => string '58' (length=2)
      'uid' => string '1' (length=1)
      'item_id' => string '6' (length=1)
      'item_name' => string 'kubek #1' (length=8)
      'price' => string '10.01' (length=5)
      'time' => string '1373978751' (length=10)
  3 => 
    array (size=6)
      'id' => string '56' (length=2)
      'uid' => string '1' (length=1)
      'item_id' => string '7' (length=1)
      'item_name' => string 'ewr' (length=3)
      'price' => string '1.05' (length=4)
      'time' => string '1373975032' (length=10)

and i need to turn this array into something like:

      0 => 
    array (size=6)
      'id' => string '59' (length=2)
      'uid' => string '1' (length=1)
      'item_id' => string '5' (length=1)
      'item_name' => string 'dfgdfg' (length=6)
      'price' => string '14.91' (length=5)
      'time' => string '1373978756' (length=10)
      'q' => 2 

  1 => 
    array (size=6)
      'id' => string '58' (length=2)
      'uid' => string '1' (length=1)
      'item_id' => string '6' (length=1)
      'item_name' => string 'kubek #1' (length=8)
      'price' => string '10.01' (length=5)
      'time' => string '1373978751' (length=10) 
      'q' => 1 
  2 => 
    array (size=6)
      'id' => string '56' (length=2)
      'uid' => string '1' (length=1)
      'item_id' => string '7' (length=1)
      'item_name' => string 'ewr' (length=3)
      'price' => string '1.05' (length=4)
      'time' => string '1373975032' (length=10) 
      'q' => 1

need to count how many specific values is into array and place them into the new one. At this moment i try to do this in this way but it wont work well

foreach ($b as $k => $v) {
        $bas[$k]['q'] = array_count_values($v['item_id']);
    }

Upvotes: 0

Views: 111

Answers (1)

Pieter
Pieter

Reputation: 1833

If you're using a database, you can use this query:

 SELECT *, count(item_id) AS quantity FROM table GROUP BY item_id

Upvotes: 1

Related Questions