2013-04-22 140 views
1

我正试图解析链接下面的JSON文件,但我仍然无法弄清楚解析和显示它与foreach。JSON解析与PHP foreach

data: [ 
{ 
id: "1072", 
nik: "013977", 
status: "", 
name: "RAKHMAT KUSNADI", 
birthdate: "1983-10-21", 
email: "[email protected]", 
first_login: "0", 
is_juri: "0", 
what_juri: "", 
categorized: "0", 
back_stage: "0", 
placement: [ 
{ 
rel_id: "1102", 
employee_id: "1072", 
department_id: "101", 
dept: "Chip", 
position_id: "1", 
position: "" 
} 
], 
profile_pics: "link" 
}, 
{ 
id: "1069", 
nik: "013377", 
status: "", 
name: "RENATA MARINGKA", 
birthdate: "1987-05-20", 
email: "", 
first_login: "1", 
is_juri: "0", 
what_juri: "", 
categorized: "0", 
back_stage: "0", 
placement: [ 
{ 
rel_id: "1099", 
employee_id: "1069", 
department_id: "101", 
dept: "Chip", 
position_id: "1", 
position: "" 
} 
], 
profile_pics: "link" 
}, 
] 
} 

我想要显示的姓名和profile_pics地方部门ID是101

有谁知道如何用foreach解析呢?

+0

修订问题 – 2013-04-24 07:48:01

+0

确保您的JSON验证。 http://jsonlint.com/ – Fred 2014-10-20 13:33:10

回答

2

第一步是转换成数组

$data = json_decode($json); 

一旦你得到了数组,那么你可以遍历并检查值

$keepers = array(); 
foreach ($data as $item) { 
    if ($item->placement->department_id == 101) { 
    $keepers[] = $item; 
    } 
} 
5

重新发明轮子,是我们?为什么不直接使用:

$jsonObj = json_decode($jsonString);//returns stdClass instance, just an object 
$jsonArr = json_decode($jsonString, true);//converts object to associative array 

Read more on json_decode here ...这是很容易使用,真的

如果您的数据进行解码到一个数组,你可以通过像这样

while($item = array_shift($jsonArr)) 
{ 
    foreach ($item as $key => $value) 
    { 
     echo $key.' => '.$value."\n"; 
    } 
} 
数据环

或者简单地在对象上使用任何旧的for/foreach循环,无论如何它的可遍历对象(尽管它不实现Traversable接口)

2

使用json_decode

$arr = json_decode($jsonstring, true); 

然后使用foreach循环

foreach($arr as $val) { 
    if($val['placement']['department_id'] == "101") { 
     //display what u want 
    } 
} 
0

大概是这样的:

$data = json_decode($your_json); 

foreach($data as $object) { 
    echo 'This is the name: ' . $object->name . PHP_EOL ; 
} 
0
$data = json_decode($json, true) 

那么你一定要出什么信息你走出与foreach循环

foreach ($data->id as $id) 
{ 
echo $id; 
} 

有了,你可以设置任何变量像$data->nik as $nik或任何你想要的,然后回声回

0

USR这

foreach ($data->id as $id) 
{ 
echo $id; 
}