tags:

views:

56

answers:

2
+1  Q: 

php array count

I have a var dump of my sql query which return the following

I wanna to count in the array below that how many rows of myID = 5 are there. How would I do that. I am using php. Thanks in advance

 array
  0 => 
    object(stdClass)[17]

      public 'myID' => string '5' (length=1)
      public 'data' => string '123' (length=3)
  1 => 
    object(stdClass)[18]

      public 'myID' => string '5' (length=1)
      public 'data' => string '123' (length=3)
  2 => 
    object(stdClass)[19]

      public 'relativeTypeID' => string '2' (length=1)
      public 'data' => string '256' (length=3)
  3 => 
    object(stdClass)[20]

      public 'myID' => string '4' (length=1)
      public 'data' => string '786' (length=3)

    object(stdClass)[21]

      public 'myID' => string '4' (length=1)
      public 'data' => string '786' (length=3)
+2  A: 

Do you always have the same value of data for the same myID? In other words, is data functionally dependant on myID?

If so, you can get the database to do this for you:

SELECT myID, data, COUNT(*) AS cnt
FROM (your query here)
GROUP BY myID, data

This would give you results like the following:

myID  data   cnt
'5'   '123'  3
'2'   '256'  1
'4'   '786'  2
Mark Byers
womderful. Thanks!
My suggestion is to not use COUNT(*), as that's considered a bad practice (not very efficient in many different situations). Try doing a count( myID ). This isn't always the case (there is a fast count(*) in InnoDB, I know), but as a general rule it's safest to count on a specific column.
Travis Leleu
That should be a COUNT( star ) above, not COUNT(). And ignore the italics. My bad forgot about markdown and now I can't seem to edit my comment.
Travis Leleu
A: 

Or, you can use a foreach statement, like:

$count = 0;

foreach($arr as $item)
{
    // Given that your item is an stdClass Object you access its property with "->"
    // if an array $item["myID"] instead
    if ( $item->myID == '4' )
    {
        $count ++;
    }
}
falomir
Down vote and no comment?
falomir
The downvote wasn't mine (your solution is technically correct, so I wouldn't think it deserves a dv) but I'm guessing the criticism is that this would be very inefficient. This is a situation where it's best to do the counting in the database.
Travis Leleu