我有这个json代码:
{
"data": [
{
"name": "John",
"id": "11"
},
{
"name": "Max",
"id": "22"
},
{
"name": "Martin",
"id": "33"
},
{
"name": "Adrian",
"id": "44"
}
]
}
现在,我需要以这种方式打印所有名称和ID:
John 11
Max 22
Martin 33
Adrian 44
最简单的方法是什么?
答案 0 :(得分:4)
像这样:
$arr = json_decode($string, true); // true to retrieve an associative array
foreach($arr['data'] as $sub) {
echo $sub['name'],' ',$sub['id'],PHP_EOL;
}
输出:
John 11
Max 22
Martin 33
Adrian 44
答案 1 :(得分:1)
<?php
$a='{ "data": [ { "name": "John", "id": "11" }, { "name": "Max", "id": "22" }, { "name": "Martin", "id": "33" }, { "name": "Adrian", "id": "44" } ] }';
$b=json_decode($a);
$data=$b->{'data'};
foreach($data as $item) {
print $item->{'name'}.' '.$item->{'id'}."\n";
}
?>
对于额外的积分,Javascript版本:
objectValueList=function(x) {
var tags=[];
for (i in x) {
if(x.hasOwnProperty(i)) {
tags.push(x[i]);
}
}
return tags;
}
var a='{ "data": [ { "name": "John", "id": "11" }, { "name": "Max", "id": "22" }, { "name": "Martin", "id": "33" }, { "name": "Adrian", "id": "44" } ] }';
var b=JSON.parse(a);
var data=objectValueList(b.data);
for (x in data) {
console.log(data[x].name+" "+data[x].id);
}
答案 2 :(得分:0)
使用json_decode()
。
$data=json_decode($string);
foreach($data as $person){
foreach($person as $key=>$val){
foreach($val as $tuple)
echo $tuple." ";
echo "\r\n";
}
}
}