解析具有多个数组的JSON字符串

时间:2016-04-03 21:48:09

标签: php arrays json

我正在尝试解析此JSON字符串

$json = {"fields":{
"relationshipStatus":[{"fieldId":4,"name":"Committed"},{"fieldId":2,"name":"Dating"},{"fieldId":6,"name":"Engaged"},{"fieldId":3,"name":"Exclusive"},{"fieldId":7,"name":"Married"},{"fieldId":8,"name":"Open Relationship"},{"fieldId":5,"name":"Partnered"},{"fieldId":1,"name":"Single"}],
            "ethnicity":[{"fieldId":1,"name":"Asian"},{"fieldId":2,"name":"Black"},{"fieldId":3,"name":"Latino"},{"fieldId":4,"name":"Middle Eastern"},{"fieldId":5,"name":"Mixed"},{"fieldId":6,"name":"Native American"},{"fieldId":8,"name":"Other"},{"fieldId":9,"name":"South Asian"},{"fieldId":7,"name":"White"}],
}}

使用这个foreach循环,最终我希望能够获取数据并将其用作表单上的Select / List下拉列表。

foreach($json['fields'] as $item){
    foreach($item['relationshipStatus'] as $relationship){
        echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
    }

    foreach($item['ethnicity'] as $ethnicity){
        echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
    }
}

无论我如何尝试提取数据,我都会遇到类似以下错误:

  

注意:未定义的索引:relationshipStatus in   第126行/Applications/MAMP/htdocs/updateprofile.php警告:   为foreach()提供的参数无效   第126行/Applications/MAMP/htdocs/updateprofile.php

我做错了什么?

2 个答案:

答案 0 :(得分:1)

第一个foreach已选择relationshipStatusethnicity。也许以下更改显示我的意思:

foreach($json['fields'] as $key=>$item){
if ($key == 'relationshipStatus')
foreach($item as $relationship){
    echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
else if ($key == 'ethnicity')
foreach($item as $ethnicity){
    echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}

答案 1 :(得分:0)

在这里,您以错误的方式迭代JSON Object。您要获取的数组值实际上位于$json['fields']['relationshipStatus']之下。

var name = $json['fields']['relationshipStatus']['name'];
var fieldId = $json['fields']['relationshipStatus']['fieldId'];

=============================== OR =============== =========================

A.fink

所述
foreach($json['fields'] as $key=>$item){
if ($key == 'relationshipStatus')
foreach($item as $relationship){
    echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
else if ($key == 'ethnicity')
foreach($item as $ethnicity){
    echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}