亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何用PHP解析JSON文件?

如何用PHP解析JSON文件?

呼喚遠方 2019-05-22 14:46:46
如何用PHP解析JSON文件?我試圖使用PHP解析JSON文件。但我現在被困住了。這是我的JSON文件的內容:{    "John": {        "status":"Wait"    },    "Jennifer": {        "status":"Active"    },    "James": {        "status":"Active",        "age":56,        "count":10,        "progress":0.0029857,        "bad":0    }}這是我到目前為止所嘗試的:<?php$string = file_get_contents("/home/michael/test.json");$json_a = json_decode($string, true);echo $json_a['John'][status];echo $json_a['Jennifer'][status];但是,因為我不知道的名字(例如'John','Jennifer')和所有可用鍵和值(如'age','count')事前,我想我需要創建一些foreach循環。我會很感激這個例子。
查看完整描述

5 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

要迭代多維數組,可以使用RecursiveArrayIterator

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }}

輸出:

John:status => WaitJennifer:status => ActiveJames:status => Activeage => 56count => 10progress => 0.0029857bad => 0

在鍵盤上運行


查看完整回答
反對 回復 2019-05-22
?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

最優雅的解決方案:


$shipments = json_decode(file_get_contents("shipments.js"), true);

print_r($shipments);

請記住,json文件必須以UTF-8編碼而不使用BOM。如果文件有BOM,則json_decode將返回NULL。


或者:


$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));

echo $shipments;


查看完整回答
反對 回復 2019-05-22
?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

沒有人指出你開始的“標簽”是錯誤的,完全超出我的范圍。您正在使用{}創建對象,而可以使用[]創建數組。


[ // <-- Note that I changed this

    {

        "name" : "john", // And moved the name here.

        "status":"Wait"

    },

    {

        "name" : "Jennifer",

        "status":"Active"

    },

    {

        "name" : "James",

        "status":"Active",

        "age":56,

        "count":10,

        "progress":0.0029857,

        "bad":0

    }

] // <-- And this.

通過此更改,json將被解析為數組而不是對象。使用該數組,您可以執行任何操作,例如循環等。


查看完整回答
反對 回復 2019-05-22
  • 5 回答
  • 0 關注
  • 2081 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號