2013-04-22 90 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; 
}