0

The raw output of my object is when I do a print_r is:

Array ( [0] => stdClass Object ( [COUNT(*)] => 3 ) )

How do I get to the 3?

This object is the result of a sql query inside wordpress with the $wpdb class.

I am a noob at PHP objects. Also would like to know

  • where do I learn to do object parsing stuff like this?
  • What kind of object is this? Why is it wrapped in an Array?

UPDATE: here's the source code:

global $wpdb;
$post_count = $wpdb->get_results("SELECT COUNT(*) FROM $wpdb->posts");
print_r($post_count);
2
  • 3
    Wouldn't it make more sense to alias it in the query: SELECT count(*) AS total FROM .... Commented Apr 1, 2012 at 9:53
  • yep that's what I did below. Answered my own question. Commented Apr 1, 2012 at 9:54

2 Answers 2

3

It's not an object. It's an array containing an object. In that specific example, assuming that the variable is named $variable, you'd do this:

echo $variable[0]->{'COUNT(*)'};
Sign up to request clarification or add additional context in comments.

7 Comments

P.S. I wouldn't want to work with data like that, but does anyone else think it looks sort of pretty? :)
Is this the kind of structure that is usually returned by a sql query?
I don't use Wordpress, so I don't know how it pulls out result sets.
I didn't know you could use curly braces like that in PHP (other than in code blocks). What is this structure called?
I don't know if it has a name, but using curly brackets and quoting it allows you to use characters that would otherwise not be allowed.
|
1

I found the solution:

global $wpdb;
$post_count = $wpdb->get_results("SELECT COUNT(*) as postcount FROM $wpdb->posts");
print_r($post_count[0]->postcount);

I needed to use an alias.

Comments

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.