簡體   English   中英

將json字符串轉換為php變量

[英]get json string into php variables

我有下面的代碼,我想做的是將json值從“ total_reviews”轉換為php變量,我們可以將其稱為$ total_reviews。

但是發生了什么事,我得到一個錯誤,說

Notice: Undefined property: stdClass::$total_reviews

這是我的代碼

//URL of targeted site  
$url = "https://api.yotpo.com/products/$appkey/467/bottomline";  
//  Initiate curl
$ch = curl_init();

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
$data = json_decode($result);

echo "e<br />";
echo $data->total_reviews; 


// close curl resource, and free up system resources  
curl_close($ch);  
?>

如果我print_r結果我有以下打印

{"status":{"code":200,"message":"OK"},"response":{"bottomline":{"average_score":4.2,"total_reviews":73}}}

如果要將JSON數據作為數組,請使用json_decode()上的第二個參數將其轉換為數組。

$data = json_decode($result, true);

如果您希望將JSON數據傳遞給您,並且我認為這是作為對象,請使用

$data = json_decode($result);

echo "<br />";
echo $data->total_reviews; 

json_decode()手冊頁

但是無論哪種方式,如果這是您的JSON字符串,

{"status":
    {
        "code":200,
        "message":"OK"
    },
"response":
    {
        "bottomline":
            {
                "average_score":4.2,
                "total_reviews":73
            }
    }
}

total_reviews值為

echo $data->response->bottomline->total_reviews;

或者如果您使用參數2將完美的對象轉換為數組

echo $data['response']['bottomline']['total_reviews'];

json_decode()默認為提取到stdClass對象中。 如果需要數組,請傳遞一個真實值作為第二個參數:

$data = json_decode($result, true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM