I’m getting back a JSON string from a third party API. When I use json_decode($json, true) to put it into an array, I end up with a nested array. It seems to me it shouldn’t be like this. Can someone explain if this is correct behavior?
$obj = getStatus('100000043');
var_dump($obj);
getStatus calls the third-party API. The result of var_dump is:
string(245)
“[{“Status”:”Processing”,”OrderNum”:”87″,”InvoiceNum”:”0″,”PoNum”:”100000043″,”ShippingCost”:””,”TrackingNum”:””,”ShippingWeight”:””,”cust_num”:”123″,”entryTime”:”2012-02-02
15:19:05″,”branch”:”0″,”CustPoNum”:”43″,”brord”:”12345″}]”
Ok, so I decode to an array:
$myArray = json_decode($obj, true);
var_dump($myArray);
result is:
array(1) { [0]=> array(12) {
[“Status”]=>
string(10) “Processing”
[“OrderNum”]=>
string(5) “87686”
[“InvoiceNum”]=>
string(1) “0”
[“PaPoNum”]=>
string(9) “100000043”
[“ShippingCost”]=>
string(0) “”
[“TrackingNum”]=>
string(0) “”
[“ShippingWeight”]=>
string(0) “”
[“cust_num”]=>
string(5) “64366”
[“entryTime”]=>
string(19) “2012-02-02 15:19:05”
[“branch”]=>
string(1) “8”
[“CustPoNum”]=>
string(9) “100000043”
[“brord”]=>
string(6) “887686” } }
The array I want is nested within $myArray[0] …
How to get a value out:
$myArray[0]['Status']
From the docs and examples I would expect $myArray[‘Status’] to work.
Do i misunderstand or I’m doing something wrong or is there something funky about the API result?
with json encoded data, when you have code that starts with a square brace, then it contains data with curly braces:
[{data}], it’s always going to be a nested array.It’s simple enough to access the data using
$myArray[0]['Status'].You can also assign
$myArray[0]to$myArraylike this:Then you can access all elements of the array using this syntax: