簡體   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