【问题标题】:How To Loop Json Array In PHP如何在 PHP 中循环 Json 数组
【发布时间】:2018-08-02 03:32:39
【问题描述】:

有谁知道我如何在 PHP 中循环这个 JSON 数组?我刚试了,还是不行

[{
   //
    "data": [{
            "id": "1",
            "name": "Tiger Nixon",
            "position": "System Architect",
            "salary": "$320,800",
            "start_date": "2011/04/25",
            "office": "Edinburgh",
            "extn": "5421"
        },
        {
            "id": "2",
            "name": "Garrett Winters",
            "position": "Accountant",
            "salary": "$170,750",
            "start_date": "2011/07/25",
            "office": "Tokyo",
            "extn": "8422"
        },
        {
            "id": "3",
            "name": "Ashton Cox",
            "position": "Junior Technical Author",
            "salary": "$86,000",
            "start_date": "2009/01/12",
            "office": "San Francisco",
            "extn": "1562"
        },
        {
            "id": "4",
            "name": "Cedric Kelly",
            "position": "Senior Javascript Developer",
            "salary": "$433,060",
            "start_date": "2012/03/29",
            "office": "Edinburgh",
            "extn": "6224"
        }
    ]
}]

【问题讨论】:

标签: javascript php json


【解决方案1】:

您应该将 json 转换为数组,然后为每个 json 将对象转换为数组

$json = "current Json data";
$json = json_decode($json); //convert json to array
$json = $json[0]->data; //get all data

foreach ($json as $key => $value) {
    $value = get_object_vars($value); // convert object to array
    print_r($value)
}

【讨论】:

  • 是的,我检查了它并且工作正常,您可以按照我的脚本尝试吗?
【解决方案2】:

首先,将您的 JSON 解码为 PHP 数组,然后您可以正常循环遍历它。

$arrayItems = json_decode($jsonString)

foreach ($arrayItems as $item){
 // do something
}

【讨论】:

    【解决方案3】:

    您可以使用以下代码来迭代json格式:

    $jsonData = json_decode($data);
            foreach($jsonData as $jsonDataKey => $jsonDataValue){
                foreach($jsonDataValue as $jsonArrayKey => $jsonArrayValue){
                    echo $jsonArrayValue['id'];
                    echo $jsonArrayValue['name'];
                    echo $jsonArrayValue['position'];
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 2020-12-17
      • 2016-11-09
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多