我正在嘗試從 json 代碼中獲取結果。我已經在 jsonlint 檢查了 json 結果并且它已經過驗證。我這樣做:$result = curl_exec($curl);if(!$result){die("Connection Failure");}curl_close($curl);然后當我做 echo $result 這是結果:{"vat":{"640252":{"name":"0%","percentage":"0.00","invoice_type":"2","vat_code":"5B2","available":"1 "},"640258":{"name":"0%","percentage":"0.00","invoice_type":"1","vat_code":"1E1","available":"1"}, "640256":{"name":"21%","percentage":"21.00","invoice_type":"1","vat_code":"1A2","available":"1"}}}當我這樣做時,它確實顯示了增值稅代碼 640252 的名稱:$result2 = json_decode($result, true);echo $result2['vat']['640252']['name'];但是我無法通過 foreach 瀏覽 json。首先想創建一個帶有 id 的變量(如 640252)和一個帶有百分比的變量,并在 foreach 中回顯它們。我已經從 Stackoverflow 嘗試了很多東西,但所有的 json 輸出似乎都與我的輸出不同。我希望有人能在正確的方向上幫助我。
3 回答

慕勒3428872
TA貢獻1848條經驗 獲得超6個贊
原因是,在解碼 json 字符串后,vat 是一個帶有值數組的鍵。只需按照以下示例迭代增值稅屬性。
$data = json_decode($result, true);
foreach ($data['vat'] as $id => $item) {
echo "<pre>";
var_dump($id, $item);
echo "</pre>";
}
希望有幫助。

藍山帝景
TA貢獻1843條經驗 獲得超7個贊
<?php
$json = '... lots of JSON here ...';
$arr = json_decode($json, true);
foreach ($arr['vat'] as $id => $item) {
echo "$id -> {$item['name']}\n";
}
以您的 JSON 為例,這是我得到的輸出:
640252 -> 0%
640258 -> 0%
640256 -> 21%
如果您不需要 ID(例如640252),您可以這樣做:
foreach ($arr['vat'] as $item) {
- 3 回答
- 0 關注
- 164 瀏覽
添加回答
舉報
0/150
提交
取消