繁体   English   中英

从 curl 和 json_decode 检索数据

[英]Retrieving data from curl and json_decode

我试图从 curl 和 json_decode 结果中提取单个数据字符串,但无法正确定位数组元素:

应用程序接口:

$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);

结果:

{"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/>';

还试过:

echo 'Bid: '.$obj['Bid'].'<br/>';
echo 'Ask: '.$obj['Ask'].'<br/>';
echo 'Last: '.$obj['Last'].'<br/>';

您需要在 json_decode 中添加一个 true 参数

喜欢

json_decode($execResult, true);

否则你会得到一个带有解码数据的 stdObject 。

那么你应该可以使用 $obj['result']['Bid'] aso。

json_decode的使用有一个可选的第二个参数 - 布尔值 - 将数据作为对象或数组返回。

{"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'];

刚刚运行这个作为测试..

$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'];

其中显示:

0.043500030.04350003

使用这种方式:

echo 'Bid: '.$obj->result->Bid.'<br/>';
echo 'Ask: '.$obj->result->Ask.'<br/>';
echo 'Last: '.$obj->result->Last.'<br/>';

$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/>';

尝试使用json_decode($string, true); 作为数组

$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/>';

或使用json_decode($string); 作为对象

$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/>';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM