1

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)
1
  • Are you sure you want do a query and then use PHP to count something on that query? It makes way more sense to write a query that only returns the tuples you care about and then see how many results there are (if you are going to use the data in them, otherwise the query would better be a count query itself) Commented May 3, 2010 at 22:08

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
-1

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 ++;
    }
}

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.