I am trying to extract the individual data strings from a curl and json_decode result, but cannot manage to target the array elements correctly:
API:
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);
Result:
{"success":true,"message":"","result":{"Bid":0.04350003,"Ask":0.04395399,"Last":0.04350003}}
PHP:
echo 'Bid: '.$obj['result']['Bid'].'<br/>';
echo 'Ask: '.$obj['result']['Ask'].'<br/>';
echo 'Last: '.$obj['result']['Last'].'<br/>';
Also tried:
echo 'Bid: '.$obj['Bid'].'<br/>';
echo 'Ask: '.$obj['Ask'].'<br/>';
echo 'Last: '.$obj['Last'].'<br/>';
You need to add a true parameter to your json_decode
Like
json_decode($execResult, true);
Else you get a stdObject with the decoded data.
Then you should be able to use $obj['result']['Bid'] aso.
The use of json_decode
has an optional second parameter - boolean - that either returns the data as an object or as an array.
{"success":true,"message":"","result":{"Bid":0.04350003,"Ask":0.04395399,"Last":0.04350003}}
$obj = json_decode( $execResult ); /* will return an object */
echo $obj->result->Bid;
$obj = json_decode( $execResult, true ); /* will return an array */
echo $obj['result']['Bid'];
Just ran this as the test..
$data='{"success":true,"message":"","result":{"Bid":0.04350003,"Ask":0.04395399,"Last":0.04350003}}';
$obj = json_decode( $data ); /* will return an object */
echo $obj->result->Bid;
$obj = json_decode( $data, true ); /* will return an array */
echo $obj['result']['Bid'];
which displayed:
0.043500030.04350003
Use this way:
echo 'Bid: '.$obj->result->Bid.'<br/>';
echo 'Ask: '.$obj->result->Ask.'<br/>';
echo 'Last: '.$obj->result->Last.'<br/>';
let
$json = '{"success":true,"message":"","result":{"Bid":0.04350003,"Ask":0.04395399,"Last":0.04350003}}';
$obj = json_decode($json, true);// decode and convert it in array
echo 'Bid: '.$obj['result']['Bid'].'<br/>';
echo 'Ask: '.$obj['result']['Ask'].'<br/>';
echo 'Last: '.$obj['result']['Last'].'<br/>';
Try using json_decode($string, true);
as an array
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult, true);
echo 'Bid: '.$obj['result']['Bid'].'<br/>';
echo 'Ask: '.$obj['result']['Ask'].'<br/>';
echo 'Last: '.$obj['result']['Last'].'<br/>';
OR using json_decode($string);
as an object
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);
echo 'Bid: '.$obj->result->Bid.'<br/>';
echo 'Ask: '.$obj->result->Ask.'<br/>';
echo 'Last: '.$obj->result->Last.'<br/>';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.