从curl和json_decode中检索数据

时间:2018-01-25 13:30:31

标签: php arrays json decode

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

API:

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

5 个答案:

答案 0 :(得分:3)

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

喜欢

json_decode($execResult, true);

否则,您将获得包含已解码数据的stdObject。

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

答案 1 :(得分:2)

使用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

答案 2 :(得分:1)

使用这种方式:

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

尝试将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/>';