Traverse an object's properties with dynamic names - php

I am trying to get the current trends from the twitter api (but that's sorta irrelevant).
I receive the information as an object. In this situation some of the properties that I need to access, are dates from when the trends were last updated, therefore I can't hard code the property names.
Here's an example incase I didn't explain myself well, which I fear I didn't :(
stdClass Object
(
[2011-03-09 02:45] => Array
(
[0] => stdClass Object
(
[promoted_content] =>
[events] =>
[query] => RIP Mike Starr
[name] => RIP Mike Starr
)
[1] => stdClass Object
(
[promoted_content] =>
[events] =>
[query] => Mac & Cheese
[name] => Mac & Cheese
)
Note: This is not the full object

You can traverse an object's properties using get_object_vars()
$fooBar = new stdClass();
$fooBar->apple = 'red';
$fooBar->pear = 'green';
foreach(get_object_vars($fooBar) as $property => $value) {
echo $property . " = " . $value . "\n";
}
// Output
// apple = red
// pear = green

Are you getting this data as JSON? If so, check out the second argument to json_decode, which lets you get the results back as an associative array instead of as an object. This will let you use the normal loop constructs, like foreach and obtain keys using array_keys.
If you aren't getting this data via JSON, you can consider using Reflection to grab the properties of an object. (edit #2: I'm not sure if this will work on stdClass or not, actually...)

Related

PHP Get / check value from associative array in array of individual stdClass Objects

Having real issues with this. I want to be able to get a value from this data which is returned via an API.
ie get value by
$CM_user_customfields['Organisation'],
$CM_user_customfields->Organisation.
is that even possible? I have tried loops and rebuilding the array but i always end up with a similar results and perhaps overthinking it.
I can't use the [int] => as the number of custom fields will be changing a lot.
$CM_user_customfields = $CM_details->response->CustomFields ;
echo '<pre>' . print_r( $CM_user_customfields, true ) . '</pre>';
// returns
Array
(
[0] => stdClass Object
(
[Key] => Job Title
[Value] => Designer / developer
)
[1] => stdClass Object
(
[Key] => Organisation
[Value] => Jynk
)
[2] => stdClass Object
(
[Key] => liasoncontact
[Value] => Yes
)
[3] => stdClass Object
...
many thanks, D.
I recommend convert to associative array first:
foreach($CM_user_customfields as $e) {
$arr[$e->Key] = $e->Value;
}
Now you can access it as:
echo $arr['Organisation'];
You can also achieve it by: (PHP 7 can convert stdClass and will do the trick)
$arr = array_combine(array_column($CM_user_customfields, "Key"), array_column($CM_user_customfields, "Value")));

How to grab value from array

I am pulling an array from my DB that is saved in this format:
[categories] => [
{"category":"Exit Sign"},
{"category":"Leaving"},
{"category":"Illuminated"},
{"category":"Sign"},
{"category":"Red"},
{"category":"Warning Sign"},
{"category":"Above"}
]
How can I loop through each {} and get the category?
Edit: I have attempted passing each JSON array from my DB through json_decode() but I am getting the following error "json_decode() expects parameter 1 to be string, array given..." Any idea what would cause this?
Edit 2: Here is the var_dump output for just one row in my DB:
array(1) {
["categories"]=>
string(845) "[{"category":"Built Structure"},{"category":"The Americas"},{"category":"Sky"},{"category":"New York City"},{"category":"Manhattan - New York City"},{"category":"USA"},{"category":"History"},{"category":"Suspension Bridge"},{"category":"Brooklyn - New York"},{"category":"Brooklyn Bridge"},{"category":"Scenics"},{"category":"Skyscraper"},{"category":"River"},{"category":"Downtown District"},{"category":"East River"},{"category":"Cityscape"},{"category":"Bridge - Man Made Structure"},{"category":"City"},{"category":"Lighting Equipment"},{"category":"Arch"},{"category":"Urban Skyline"},{"category":"Architecture"},{"category":"Sunset"},{"category":"Night"},{"category":"Modern"},{"category":"Urban Scene"},{"category":"Tower"},{"category":"Famous Place"},{"category":"Gate"},{"category":"Outdoors"},{"category":"East"},{"category":"Travel"}]"
}
Got it! I had to pass $array['categories'] into json_decode and then it worked properly. Thanks everyone for your help!
Well, So you are new to this world. You are welcome.
Let your array value is names as $json. This value is a json format, so for access this value you need to decode them. You need to use a function called json_decode, which has two parameter, the first one is string where you pass your variable json, an second one is bool where you pass true or false.
You have to pass when you want your array as associative not object. Here i ignore the second option, so my return array is object.
After decoding your json string you have an array, now you have to use a loop foreach to browse all the elements of the array. As you can see in the resultant array below, the array is multi-dimensional so after applying a foreach loop you just reach the first depth. For getting the value of category you should need to use -> after $val which is the first depth array.
$json = '[{"category":"Exit Sign"},{"category":"Leaving"},{"category":"Illuminated"},{"category":"Sign"},{"category":"Red"},{"category":"Warning Sign"},{"category":"Above"}]';
$arr = json_decode($json); //Also you can pass $yourArr['categories'];
foreach($arr as $val){
echo $val->category."<br/>";
}
After decoding your array looks like:
Array
(
[0] => stdClass Object
(
[category] => Exit Sign
)
[1] => stdClass Object
(
[category] => Leaving
)
[2] => stdClass Object
(
[category] => Illuminated
)
[3] => stdClass Object
(
[category] => Sign
)
[4] => stdClass Object
(
[category] => Red
)
[5] => stdClass Object
(
[category] => Warning Sign
)
[6] => stdClass Object
(
[category] => Above
)
)
Result:
Exit Sign
Leaving
Illuminated
Sign
Red
Warning Sign
Above

Parsing a timestamp based PHP std class obkect

I have a PHP standard class object converted from json_decode of a REST call on an API which looks like :
Array
(
[1437688713] => stdClass Object
(
[handle] => Keep it logically awesome.
[id] => 377748
[ping] => stdClass Object
(
[url] => https://api.me.com
[id] => 377748
[name] => web
[active] => 1
[events] => Array
(
[0] => data_new
[1] => data_old
)
So far i had no issues in parsing any of the PHP objects. However this one is failing because i can not access the nested object elements using a key since 1437688713 is not assigned to a key and accessing an object is failing if i try to do this:
$object->1437688713->handle
Is there a way to access these elements ?
Update: one more thing, i would never know this value (1437688713) in advance. Just like a key. All i get is a stdclass object which i have to parse.
The outer part of your data is an array, not an object. Try:
$array['1437688713']->handle;
or if you don't know the key, you can iterate over the array (handy if it may contain multiple objects too):
foreach ($array as $key => $object) {
echo $key; // outputs: 1437688713
echo $object->handle; // outputs: Keep it logically awesome.
}
Get the first item from $object array
$first_key = key($object);
Use it with your response array,
$object[$first_key]->handle;
Or, the first element of array
$first_pair = reset($object)->handle;

Explanation for traversing object variables of simplexml node list

I have this
$xml = new SimpleXMLElement($output);
$names = $xml->param->value->array->data;
Here is the output
SimpleXMLElement Object
(
[value] => Array
(
[0] => SimpleXMLElement Object
(
[struct] => SimpleXMLElement Object
(
[member] => SimpleXMLElement Object
(
[name] => school
[value] => SimpleXMLElement Object
(
[struct] => SimpleXMLElement Object
(
[member] => Array
(
[0] => SimpleXMLElement Object
(
[name] => schoolid
[value] => SimpleXMLElement Object
(
[string] => 49961
)
)
[1] => SimpleXMLElement Object
(
[name] => schoolname
[value] => SimpleXMLElement Object
(
[string] => Millersville Elementary School
)
)
I am trying to get to the "schoolname" value
using
for($i=0;$i<count($names);$i++) {
echo $names[0][$i]->struct->member->value->struct->member[0]->value.'<br>';
}
I've also tried as string($names[0]etc.) with no success. I think I am messing up the order in the beginning with $names[0][$i]??
Any help is much appreciated!
Consider learning XPath if you feel lazy. It's the easy way to address your issue if you don't want to loose it with a never ending streak of ->'s :)
Learning XPath is also an investment. When you deal with XML you need to know it. It's the SQL of XML or DOM (see DOMXPath).
I know this is not really an answer but spending some time and what I pointed out here is worth it and will also solve you problem.
Here is the solution using xpath to get fieldname and values
$cols = $xml->xpath('//member/value/struct/member/name');
$names = $xml->xpath('//member/value/struct/member/value/*');
for($i=0;$i<count($cols);$i++) {
echo $cols[$i].' = '.$names[$i].'<br>';
}
xpath is a must for anyone dealing with xml!
The result $name is a mix of valuse (object and array).
Try to convert $name to an object only or an array only.
The example you posted is not complete, could not try to chaqge it.
I recently had a similar issue, I ended up writing something that flattened the whole structure to be arrays within arrays, much more travesrsable, but to the matter at hand, I often find it helpful to var_dump/print_r each stage and build it up level by level.
$names is an object so it would seem to me the reference you want is:
$names->value[0]->struct->member->value->struct->member['value'][1]->value;
Edit: I've ignored the looping part for now as I think you'll need to re-evaluate your count(), it seems it needs to be count($names->value), which is the array of schools if I'm correct, in which case the $i would go in the first [0].

How to access stdclass object after a specific key value pair?

I have a stdclass object as shown below:
stdClass Object
(
[text] => Parent
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Laurence W. Lane Jr.
[url] => http://www.freebase.com/view/m/0c02911
)
)
)
I iterate over multiple such objects, some of which have
stdClass Object
(
[text] => Named after
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Stanford
[url] => SomeURL
)
)
)
I was wondering how I would access the "values" object if it comes after a "text" that has "Parent" as its value?
there are serveral ways to turn it to array:
First Solution:
$value = get_object_vars($object);
Second Solution:
$value = (array) $object;
Third Solution
$value = json_decode(json_encode($object), true);
to get value of converted array
echo $value['values']['0']['id'];
The alternate way to access objects var without convert the object, try
$object->values->{'0'}->id
Expanding (or rather minimalizing) upon answer by Somwang Souksavatd, I like accessing Object values like this:
echo get_object_vars($object)['values']['0']['id'];
I had the same issue, still not so sure why but I was able to get it working using this workaround:
$k2 ="1";
$elements = json_decode('{"id":"1","name":"User1"}');
//$elements['id'] == $k2; //****Not Working
$tmp = (object)$elements;
$tmp = $tmp ->id; //****Working
//$tmp =$elements['id'] ; //****Not Working
return $tmp == $k2;
I have to say that sometimes accessing the element as array works and some times not,(On PHP7 it worked for me but on PHP5.6 it didn't).
$elements can be Array to but I chose to demonstrate with json string.
I hope this helps somehow !!!
$Obj=stdClass Object
(
[text] => Named after
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Stanford
[url] => SomeURL
)
)
)
$Values= $result->values;
$Item = $Values[0];
$id=$Item->id;
$text = $Item->text;
$url=$Item->url;
I'm doing the same thing and all I did was this;
<?php
$stdObject = json_decode($stdClassObject);
print $stdObject->values[0]->id;
this can help you accessing subarrays in php using codeigniter framework
foreach ($cassule['tarefa'][0] as $tarefa => $novo_puto_ultimos_30_dias) {
echo $novo_puto_ultimos_30_dias;
What you are looking for is the Object['values'][0]: 'values' is the keymap just like 'text', and [0] is the index inside that array you wish to access. so if you would like to get the id deep in the nest, you'd have to do something like
Object['values'][0]['id']
or
Object['values'][0]->id
which should give you /m/0c02911. But I have no idea how you are doing your loop, so you will have to adjust it to your needs and place proper variables where they need to go in that code in your loop. Not exactly sure which language you are working with.

Categories