Steve
Steve

Reputation: 1765

Wordpress: how to grab an array value from a print_r($object)

In a Wordpress page template, I'm using:

<?php
    global $wpdb;
    $sql = "SELECT COUNT(`meta_key`) FROM `wp_usermeta` WHERE `meta_key` = 'mepr-address-state' && `meta_value` = 'NSW';";
    $myrows = $wpdb->get_results($sql);
    print_r($myrows[0]);
?>

This outputs:

stdClass Object ( [COUNT(`meta_key`)] => 764 )

How do I output / print only the value 764 using an alternative to print_r($myrows[0]); please?

Upvotes: 0

Views: 116

Answers (1)

Nick
Nick

Reputation: 147196

You can get the value you want with

echo $myrows[0]->{'COUNT(`meta_key`)'};

But I would really recommend just changing your query to something like this, using an alias for the COUNT(...):

$sql = "SELECT COUNT(`meta_key`) AS meta_count FROM `wp_usermeta` WHERE `meta_key` = 'mepr-address-state' && `meta_value` = 'NSW';";

Then you can just use

echo $myrows[0]->meta_count;

Upvotes: 1

Related Questions