Trying to use some decoded json data, but I'm unable to extract it to use. I've looked at other examples that should work, but haven't worked for me.
What am I missing?
(I'm trying to do what is in the first answer of How to parse json response from CURL )
Raw JSON
{"CustomerOriginId":123456}
JSON Decode:
$result = json_decode($head, true);
Print_R results (print_r($result);):
Array ( [CustomerOriginId] => 123456 )
Var_Dump results (var_dump($result);):
array(1) { ["CustomerOriginId"]=> int(123456) }
My attempts to extract the data for use:
Attempt 1
Attempt 1 Code:
$test45 = $result["CustomerOriginID"];
echo $test45;
Attempt 1 Error:
Notice: Undefined index: CustomerOriginID
Attempt 2
Attempt 2 Code:
$test46 = $result['CustomerOriginID'];
echo $test46;
Attempt 2 Result:
Notice: Undefined index: CustomerOriginID
Attempt 3
Attempt 3 Code:
$test47 = $result[0]['CustomerOriginID'];
echo $test47;
Attempt 3 Result:
Notice: Undefined offset: 0
Attempt 4
Attempt 4 Code:
$test48 = $result[1]['CustomerOriginID'];
echo $test48;
Attempt 4 Result:
Notice: Undefined offset: 1
I'm sure it's something small, but I haven't found an answer as of yet.
Cheers!
The index for your array is "CustomerOriginId", not "CustomerOriginID" (note the case).
$json = '{"CustomerOriginId":123456}';
$array = json_decode($json, true);
print $array['CustomerOriginId']; // outputs 123456
Undefined Index usually means you are accessing the array value the wrong way. The index must match CustomerOriginId
or it will be undefined.
Try this:
$json='{ "CustomerOriginId" : 123456 }';
$result = json_decode($json, true);
$CustomerOriginId = $result['CustomerOriginId'];
echo 'CustomerOriginId = '.$CustomerOriginId;
or without associative array
$json='{ "CustomerOriginId" : 123456 }';
$result = json_decode($json);
$CustomerOriginId = $result->CustomerOriginId;
echo 'CustomerOriginId = '.$CustomerOriginId;
this works for me:
$x = json_decode('{"CustomerOriginId":123456}', true);
print_r($x);
print $x['CustomerOriginId'];
output:
Array
(
[CustomerOriginId] => 123456
)
123456