我希望你能幫助我解決這個可能很簡單的問題。所以我正在嘗試訪問下面的 json 檔案的資料:
[
{
"value": "12"
},
{
"value": "94338"
},
{
"value": "3.97"
},
{
"value": "416"
}
]
所以我已經解碼了json檔案......
<?php
$json_string = file_get_contents("myjson.json");
$json_array = json_decode($json_string, true);
print_r($json_array);
?>
...這給了我以下結果:
Array ( [0] => Array ( [value] => 12 ) [1] => Array ( [value] => 94338 ) [2] => Array ( [value] => 3.97 ) [3] => Array ( [value] => 416 ) [4] => Array ( [value] => 230 ) [5] => Array ( [value] => 0.05 ) [6] => Array ( [value] => 0 ) [7] => Array ( [value] => 440 ) [8] => Array ( [value] => 230 ) [9] => Array ( [value] => 0.05 ) [10] => Array ( [value] => 0 ) [11] => Array ( [value] => 228 ) [12] => Array ( [value] => 12 ) )
到目前為止一切順利:) 但是我現在如何訪問 json 檔案的值?換句話說,我怎樣才能得到這些值——例如 12 或 94338。
提前謝謝了。
uj5u.com熱心網友回復:
您可以使用基本的foreach回圈訪問所需的資料。
foreach ($json_array as $item) {
// you have access to the value here
echo $item['value'];
}
uj5u.com熱心網友回復:
$json_array[0], $json_array[1]
等會給你具體的價值
$colors = ["Red", "Green", "Blue"];
$colors[0] 會給你“紅色” $colors[1] 會給你“綠色”
如果您有嵌套陣列,例如
$colors = [["Red"], ["Green", "Blue"]];
$colors[0] will give you ["Red"]
$colors[0][0] will give you "Red"
$colors[1] will give you ["Green", "Blue"]
$colors[1][0] will give you "Green"
索引可以是您的示例中的字串:
$colors = ["value" => ["Red"]];
$colors["value"] will give you ["Red"]
$colors["value"][0] will give you "Red"
如果你想遍歷你的陣列,只需使用 for 或 foreach 回圈
foreach ($json_array as $key => $value) {
echo $key;
echo $value;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/431217.html
