I'm struggling to parse the below data using PHP. An API returns it, and I've tried various syntaxes. How do I return the data in a non-object way? Or, what's the syntax to call the data using the stdClass?
Could I convert this to one data based array, or even two? I'm lost when it comes to object-based data sets.
stdClass Object
(
[0] => stdClass Object
(
[district] => stdClass Object
(
[state] => NY
[number] => 29
)
)
[1] => stdClass Object
(
[district] => stdClass Object
(
[state] => NY
[number] => 26
)
)
)
When i create the object on my own, and then do a var_dump, I get this:
object(stdClass)#8 (2) {
[0]=>
object(stdClass)#4 (1) {
["district"]=>
object(stdClass)#5 (2) {
["state"]=>
string(2) "NY"
["number"]=>
string(2) "29"
}
}
[1]=>
object(stdClass)#6 (1) {
["district"]=>
object(stdClass)#7 (2) {
["state"]=>
string(2) "NY"
["number"]=>
string(2) "26"
}
}
}
They are probably casting arrays to objects in their code (
$object = (object) $array
). This has the advantage that it will be passed by reference from now on (as is the default with objects) and the disadvantage that the object is completely useless (members cannot start with numbers - see the regex in PHP's docs) until you cast it back (PHP does allow some very mysterious things):Use:
Basically You're short-cutting assigning a string to a variable, then using that variable as your object accessor.
This solution from soulmerge just worked fine for me:
Thanks a lot!!
I'm looking at their code now, and unfortunately, they've not exposed the option in their class for you to request the data as a associative array tree vs a stdClass object tree.
The "problem" is at line 96 in class.sunlightlabs.php
You have a couple options.
#1 in action
#2 in action
You could also work with their class directly via some creative application of patterns, but they make heavy use of sublcasses already which complicates it quite a bit, so I'd stick to one of these two solutions.
You can iterate through the object like this:
The user 'null' suggested this in the comments, but want to put it here so it's not missed so easly.
The best option is to pass TRUE as the second param in json_decode i.e. json_decode($data, TRUE) which makes it return associative arrays instead of classes. So if you have access to the source code – make that change.