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);
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(*)'};
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.
Related
I am trying to print a number from an array. But when i do this:
echo $results[0][0];
i get error.I tried to print the whole array using print_r() function
echo print_r($results);
Then i get this result:
Array ( [0] => stdClass Object ( [lastOrderProcessedNumber] => 109089875875875 ) ) 1
I just need to print "109089875875875" this number
How can i do that?
Thank you in advance
print_r() is a great way to inspect the contents of a variable. What it is showing you is that your variable holds an array whose first element (at index 0) is an object with an lastOrderProcessedNumber attribute. In PHP, you use -> to access object properties, so you should be able to retrieve the 109089875875875 value like this:
$results[0]->lastOrderProcessedNumber
As you can see from the print_r result, the indexed result is an object:
// $results is an 'Array' (access with square brackets)
Array
(
// Index 0 is an Object (access with arrow operator)
[0] => stdClass Object
(
[lastOrderProcessedNumber] => 109089875875875
)
)
This means you have to access the property through the arrow operator, like so:
$results[0]->lastOrderProcessedNumber
If you're expecting to only have one result, or to grab the first result from $results, you can make use of reset:
reset($results)->lastOrderProcessedNumber
If you see $results is an array of objects, that means that $results[0] is an object, not an array, so you can't access its attributes as an array but instead as an object. Like this:
$results[0]->lastOrderProcessedNumber;
I got the following array (the array is retrieved through a db query). Now, my question is, how do I get a single element like e_domains from the array mentioned below:
stdClass Object
(
[id] => 1
[uni_origin] => Aachen
[e_domains] => rwth-aachen.de
)
I got the output shown above by running the following line of codes:
if ($results ) {
foreach ( $results as $result ){
echo'<pre>'; print_r($result) ;
}
}
First off, that's not an array, that's an object. Like it says: "stdClass Object".
Access object properties like this:
$object->property_name
In your case, it would be:
$result->e_domains
There are much more to learn on the subject, like static properties, visibility etc. In your case, the above example will work.
Read more about classes and objects in the manual: http://php.net/manual/en/language.oop5.basic.php
Try this:
$e_domains = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
Hope it helpt.
Im having a hard time to read some data that i get from joomla 2.5. First i have created a module that stores data on DB as a json. So first i read from DB linke:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('params')));
$query->from($db->quoteName('#__modules'));
$query->where($db->quoteName('module') . ' = '. $db->quote('mod_products'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
and the result that i get as an array that contain objects, and each object has json data.
below is the arrray that i get from the query:
Array
(
[0] => stdClass Object
(
[params] => {
"product_name":"Sangiovese",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"Red",
"isvisible":"1"
}
)
[1] => stdClass Object
(
[params] => {
"product_name":"Syrah",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"Red",
"isvisible":"0",
}
)
[2] => stdClass Object
(
[params] => {
"product_name":"Merlot",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"Red",
"isvisible":"0"
}
)
[3] => stdClass Object
(
[params] => {
"product_name":"Vermentino",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"White",
"isvisible":"0"
}
)
);
So what i want to do is to access the data within each param for examle:
PS: Array name is $results.
,
EX: i want to access product_name of each of the products that are on this array, or subtitle and so on.
so i did something like this, but its not working, i know i am not doing it right, but i hope someone can help me, and i would really appruciate it.
foreach( $results as $result )
{
echo $result->prams->product_name;
}
Error that shows when this code gets executed:
Notice: Trying to get property of non-object in
I really would need some advice on this.
Thank you!
Every item in your list is an object:
[0] => stdClass Object
[1] => stdClass Object
And every object has a params property which is a string containing JSON data.
You need to use json_decode built-in function to convert JSON string to an object or array.
Try this approach:
$paramsDecoded = json_decode($result->params, true);
print $paramsDecoded['product_name'];
Hello and thanks to all who helped,
I managed to make it functional.
So im gonna post here all the code for everyone else that passes on the same waters and needs help.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('params')));
$query->from($db->quoteName('#__modules'));
$query->where($db->quoteName('module') . ' = '. $db->quote('mod_products') .' AND '. $db->quoteName('language') . ' <> '. $db->quote('en-GB'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
$count = count($results);
What i did to make the functionality i needed:
for ($i=0; $i < $count; $i++) {
$json = $results[$i]->params;
$product = json_decode($json);
// code here, example
echo $product->product_subtitle;
}
So, yes. I needed to decode using json_decode first, before using it on other parts of the code.
Thanks for helping. Hope this posts helps other developers who same as me, will have difficulties working with the way Joomla manipulates objects stored in database.
Using json_decode, I've ended up with an object that looks like this:
$data->foo->bar->1234567->id
I want to access id. There are two problems, both with the number 1234567:
It's an illegal property name.
The number will differ each time, and I can't predict what the number will be. I need a way of accessing id, even when I don't know the number.
I know I can overcome problem (1) with curly braces, but I don't know how to overcome (2). I don't want to use get_object_vars, because the object is likely to be very large, and that function is very slow.
My current solution is simply
foreach ($data->foo->bar as $id); but that feels rather hacky. Is there a better way?
From my comment above, using json_decode(,true) and then resetting.
The example json array looks like:
Array (
[foo] => Array (
[bar] => Array (
[1234567] => Array (
[id] => 1234
)
)
)
)
The code:
<?php
$data = json_decode('{"foo":{"bar":{"1234567":{"id":1234}}}}', true);
reset($data['foo']['bar']);
$number = key($data['foo']['bar']);
echo $data['foo']['bar'][$number]['id'];
Output: 1234
In case you don't need the whole array anymore and only want to get the id you can get it like this:
<?php
$data = json_decode('{"foo":{"bar":{"1234567":{"id":1234}}}}', true);
echo array_shift($data['foo']['bar'])['id'];
Only works if the unknown key is the first element of bar. array_shift removes the element from $data.
<?
stdClass Object
(
[image_header] => Array
(
[0] => stdClass Object
(
[img] => /headers/header.jpg
)
)
)
?>
Object name image_header is variable, so it can be any string. Can I access this string without knowing what it is?
#Jon his answer was satisfying for me.
For others who want to use variable objectnames this way:
To acces this object with the variablename I had to use curly brackets:
$key = key(get_object_vars($_json));
$_json->{$key}[0]->img;
You can do it conveniently with get_object_vars:
$propertyName = key(get_object_vars($object));
If you don't know what the name of the property is, you can use PHP's Reflection classes, or more simply use get_object_vars().
get_object_vars() is probably what you're looking for here - it "Returns an associative array of defined object accessible non-static properties for the specified object in scope. If a property has not been assigned a value, it will be returned with a NULL value." So, you get the property names and their values returned in an associative array.
Alternatively, you could use some of PHP's reflection magic, although it might be a bit overkill here, depending on your end goal. The reflection classes are very powerful, and may be worth using if you have more complex requirements for what you're trying to achieve. As an example:
// let's say $obj is the object you provided in your question
// Instantiate the reflection object
$reflector = new ReflectionClass($obj);
// Get properties of $obj, returned as an array of ReflectionProperty objects
$properties = $reflector->getProperties();
foreach ( $properties as $property ) {
echo $property->getName(); // In your example, this would echo 'image_header'
}
There are a couple of possibilities. If you're using json_decode() you can pass true in as the second parameter to parse the data as an associative array.
$data = json_decode($myJson, true);
print_r( $data['image_header'] );
You can also access an object property from a variable like this.
$myProperty = 'image_header';
print_r( $data->$myProperty );
If by "you don't know what it is" you mean you don't know the key at all you can use my first example and use array_values() to get the values by index.
$values = array_values($data);
// image_header
print_r( $values[0] );