1

我试图从链接解析下面的 json 文件,但我仍然无法弄清楚解析并使用 foreach 显示它。

data: [
{
id: "1072",
nik: "013977",
status: "",
name: "RAKHMAT KUSNADI",
birthdate: "1983-10-21",
email: "rakhmat.koes@gmail.com",
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"
},
]
}

我想显示部门 ID 为 101 的名称和 profile_pics。

有人知道如何用foreach解析它吗?

4

6 回答 6

5

重新发明轮子,是吗?为什么不简单地使用:

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

json_decode在此处阅读更多内容......它非常易于使用,真的

如果将数据解码为数组,则可以像这样遍历数据

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

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

于 2013-04-22T11:02:43.050 回答
2

使用 json_decode

  $arr = json_decode($jsonstring, true);

然后使用 foreach 循环

foreach($arr as $val) {
    if($val['placement']['department_id'] == "101") {
       //display what u want
    }
}
于 2013-04-22T11:02:45.043 回答
2

第一步是转换为数组

$data = json_decode($json);

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

$keepers = array();
foreach ($data as $item) {
  if ($item->placement->department_id == 101) {
    $keepers[] = $item;
  }
}
于 2013-04-22T10:59:08.383 回答
0

使用这个

foreach ($data->id as $id)
{
echo $id;
}
于 2014-04-23T07:05:00.817 回答
0

大概是这样的:

$data = json_decode($your_json);

foreach($data as $object) {
    echo 'This is the name: ' . $object->name . PHP_EOL ;
}
于 2013-04-22T11:02:53.967 回答
0
$data = json_decode($json, true)

然后无论你想要什么信息,你都可以使用 foreach 循环

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

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

于 2013-04-22T11:03:27.273 回答