如何在PHP中获取JSON中的所有密钥?
问题描述:
How do I get all of the keys and loop through them, echoing each one, from a JSON object array?
Here is my code:
/* SAMPLE JSON THAT IS SENT
$mystring = '{
"display_name": "Silverware",
"fields": [
{
"field_name": "Age",
"sort_order": 1,
"required": 0,
"view_type": "text",
"description": "",
"multi_value": 0,
"char_count": 255
},
{
"field_name": "Brand",
"sort_order": 2,
"required": 0,
"view_type": "multiselect",
"description": "",
"multi_value": 1,
"char_count": 255
}
]
}';
*/
$json = json_decode($HTTP_RAW_POST_DATA);
$arr = $json->{'fields'};
// This is how I print a specific value
//print $arr[0]->{'field_name'};
Adding the following isn't working for me:
foreach ($arr as $k => $v) {
echo $k', ';
}
如何从JSON对象数组中获取所有键并循环遍历每个键,并回显每个键?
/ * SAMPLE JSON SENT
$ mystring ='{
“display_name”:“ Silverware“,
”字段“:[
{
”field_name“:”Age“,
”sort_order“:1,
”required“:0,
”view_type“:”text“,\ n“description”:“”,
“multi_value”:0,
“char_count”:255
},
{
“field_name”:“Brand”,
“sort_order”:2,
“required”:0,
“view_type”:“multiselect”,
“description”:“”,
“multi_value”:1,
“
”“char_count”:255
}
]
}' ;
* /
$ json = json_decode($ HTTP_RAW_POST_DATA);
$ arr = $ json-> {'fields'};
//这是我打印特定值的方式
// print $ arr [0] - > {'field_name'};
code> pre>
添加以下isn' 为我工作: p>
foreach($ arr as $ k => $ v){
echo $ k',';
}
code> pre>
div>
答
Use true
for the second parameter of json_decode()
.
foreach ($j['fields'] as $field) {
$keys = array_keys($field);
foreach ($keys as $key) {
echo $key;
}
}