Getting the name of a stdClass object in PHP - php

I'm playing with an API that's giving me data back in JSON format that I then json_decode() to the following format:
[stockData] => stdClass Object
(
[data] => stdClass Object
(
[PS3] => stdClass Object
(
[2015-01-26T20:45:01Z] => stdClass Object
(
[AMU] => 999.76
[ZIT] => 3.63
)
)
)
[status] => stdClass Object
(
[code] => 200
[text] => ok
)
)
I need some way of getting the 2015-01-26T20:45:01Z (which changes all the time).
I've tried get_Class() on the object, eg:
get_Class($bawsaq->stockData->data->PS3) (actually in a foreach loop)
But all that's returned is: "stdClass" and not the name. How can I get the object's name?

It isn't actually the object's class: it's the name of the property that contains the stdClass object. So you'd need to get the first object property name from $bawsaq->stockData->data->PS3. Which is a bit tricky, actually.
It's nicer to work with arrays. If you use the $assoc parameter of json_decode, you can get an associative array instead of an object whenever a JSON object appears. This is much easier to deal with in PHP.
$bawsaq = json_decode($jsonData, true);
You can get the key name with key:
$dateTime = key($bawsaq['stockData']['data']['PS3']);

When you decode the JSON, use
$bawsaq = json_decode($json, true);
This will return associative arrays instead of stdClass objects for all the JSON objects. Then you can use
$keys = array_keys($bawsaq['stockData']['data'];
$date = $keys[0];

You can use get_object_vars method.
$obj = new stdClass();
$obj->field1 = 'value1';
print_r(get_object_vars($obj));
Result:
Array
(
[field1] => value1
)

You can use the second argument to json_decode. This will return the data as an associative array instead of an object list, so you could simply use
$input = json_decode($jsonInput, true);
$key = key($input['stockData']['data']['PS3']);
$data = $input['stockData']['data']['PS3'][$key];
or a foreach-loop. See also key on php.net.

Related

how to retrieve a stdClass Object Array thats located inside another array

I've got an array Address located inside an array $array1
[Address] => stdClass Object
(
[Address1] => xxxxxx
[City] => xxxxx
[State] => xxxxx
[Zip] => xxxxxxx
)
I attempted to call print_r($array1['Address']) but that doesnt work. Does the stdClass Object require that I call it differently?
This is my setup
I've got $array1 being set up inside a function called CALL_FUNCTION. Inside the function, I use return $array1 to get access to the array outside the function.
Outside the function, I've got this...
$array1 = array();
$array1 = CALL_FUNCTION();
If I do print_r($array1) it returns the array with the above std object array inside of it.
$array1 is not an array, it's also an object as indicated by the error:
Fatal error: Uncaught Error: Cannot use object of type stdClass as array
Having $array1 = array() doesn't do anything since you aren't using $array1 and are instantly reassigning it to the return value of CALL_FUNCTION().
Access it as an object: $array1->Address->Address1.
However, you'll want to change the name of $array1 to something like $userObject for the sake of future programmers who come across your code.
You can cast it to an array
// get your array
$array1 = CALL_FUNCTION();
// cast the stdObject to an array
$array1['Address'] = (array) $array1['Address'] ;

PHP wildcard for object key

I sometimes encounter and object like this:
stdClass Object
(
[batchcomplete] =>
[query] => stdClass Object
(
[pages] => stdClass Object
(
[48548] => stdClass Object
(
[pageid] => 48548
[ns] => 0
[title] => Dopamine
That object key 48548 is gonna be different every time so I have no way of knowing what its value is. Lets say I need to get the title (Dopamine) in this object, I would need to do something like this:
$title = $object->query->page->{*WILDCARD*}->title;
But I haven't figured out a way to do this yet. Is there a way to skip an object key like this without having to find out the value of the key?
A numeric object property is not going to work. Assuming there is only one, convert to an array and get the key:
$array = (array)$object->query->pages;
$title = $array[key($array)]->title;
Or just get the one element:
$title = current((array)$object->query->pages)->title;
If this is coming from JSON you might want to decode it as an array in the first place. If not, then maybe this:
$array = json_decode(json_encode($oject), true);
For non-numeric properties this should work:
$var = key(get_object_vars($object->query->pages));
$title = $object->query->pages->$var->title;

How to convert Std class object data to array in php

$postdata= "stdClass Object
(
[created] => 1326853478
[livemode] =>
[id] => evt_00000000000000
[type] => invoice.payment_succeeded
...........................
))";
$event = json_decode($postdata);
echo "<pre>";
print_r($event);
Can't std class object to array in php?I am using json_decode but its not working just get empty array.I am giving my result data std class object assign in variable its anything wrong that's why its showing not working?
you can use :
$array = json_decode(json_encode($data), true);
print_r($array);
The easiest way is to cast it:
$array = (array) $stdClass;
try this
$event = json_decode($data, true);
print_r($event);

Nested Array Foreach Issue

I am very basic new php learner, i having difficulty to get nested array value, here is my json result:
stdClass Object
(
[title] => Aao Raja - Gabbar Is Back | Chitrangada Singh
[link] => stdClass Object
(
[22] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fmp4&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=145.542&itag=22&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1432539432699196&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=3547894526817B37774A7838F8B68493CDD62101.3F143C74D76E8705800445A4CD4476C4F8BCD988&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => hd720
)
[43] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fwebm&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=0.000&itag=43&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1428933984759484&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=266C126464ECDB4CC0FF076CD41F07BCC4DA7E34.08D9F13B7BF7D92FD1E1963336CC7FB8F19FE899&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => medium
)
I can access the Title, but can't access the Link urls:
echo $title = $json->{'title'};
echo $link = $json->{'link'}->{'22'}->{'0'};
How can access the specific link array 22
This echo $title = $json->{'title'}; works because you are accessing an object's property and using -> is the correct way.
In this case $json->{'link'}->{'22'}->{'0'} you are trying to access an array item instead an object's property, because $json->{'link'}->{'22'} is an array and not an object. In this case, you should access it in this way: $json->{'link'}->{'22'}[0]. In order to avoid this kind of issues and, when you decode your JSON to a PHP object, you can pass true as a second parameter to the function json_decode and that will convert the whole object into an array. That way, you don't need to worry about accessing elements as object's attributes, you can access them, always, as array items. So, in this case, it would be: $json["link"]["22"][0].
You're confusing the way you access objects and arrays.
Getting the title is correct via $json->title, but the link should be $json->link->{'22'}[0] - a mixture of objects and arrays.
FYI the {'name'} notation is the same as name - only required when you are including variables in your object name e.g. {$someVar . 'name'}
I suppose you use json_decode() function. Do you know that you can get an array instead of StdClass Object? So, you can use.
<?php
$php_array = json_decode($json_string, true);

Getting value from SimpleXMLElement Object

Hi I have this following segment of XML:
......
<Result number="4" position="1" points="25">
<Driver driverId="button" url="http://en.wikipedia.org/wiki/Jenson_Button">
<GivenName>Jenson</GivenName>
<FamilyName>Button</FamilyName>
<DateOfBirth>1980-01-19</DateOfBirth>
<Nationality>British</Nationality>
</Driver>
......
I can use the following easily to get the GivenName:
$item->Driver->GivenName;
But when I use:
$item->Driver->FamilyName;
I get SimpleXMLElement Object ()
I have looked around and found that it might be something to do with passing it to a string but then I get nothing on screen. Not even SimpleXMLElement Object.
I don't understand as it's a sibling of GivenName and that works.
You get a SimpleXMLElement object in both cases, which you'll see if you use print_r():
print_r ($item->Driver->GivenName);
print_r ($item->Driver->FamilyName);
Outputs:
SimpleXMLElement Object
(
[0] => Jenson
)
SimpleXMLElement Object
(
[0] => Button
)
You can use an explicit cast to get the values as strings:
$givenNameString = (string) $item->Driver->GivenName;
$familyNameString = (string) $item->Driver->FamilyName;
To make PHP understand you have to give typecasting forcefully on object like below:
$givenName = (array) $item->Driver->GivenName;
$familyName = (array) $item->Driver->FamilyName;
print_r($givenName);
print_r($familyName);
OUTPUT :
Array ([0] => 'Jenson')
Array ([0] => 'Button')

Categories