2015-11-09 79 views
1

我想呼應了JSON陣列像這樣的對象的每一個元素:如何去通過JSON陣列的每個元素在PHP

{"request_list":[{"id":"1","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null},{"id":"3","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null}]} 

但我不能做它。我試過somethinglikethis:

$object = json_decode($json, true); 
$request_list = $object->request_list; 
foreach($request_list as $r){ 
    echo $r->name; 
    echo $r->blood_type; 
    echo $r->phone_number; 
} 

但我得到了如下錯誤:

的foreach爲無效的論點提供()

+1

擺脫真正的作爲json_deocde第二個參數,通過設置真正的你轉換對象數組。 – Styphon

+0

如果第二個參數爲true,則Json將被轉換爲php數組。刪除json_decode中的第二個參數。 –

回答

2

正如您在json_decode中將標記返回爲數組true一樣。所以,請嘗試下面的代碼。

$object = json_decode($json, true); 
$request_list = $object['request_list']; 
foreach($request_list as $r){ 
    echo $r['name']; 
    echo $r['blood_type']; 
    echo $r['phone_number']; 
} 
+0

非常感謝它工作了很好的水壩BRO sandeepsure –

+0

@YunusSımsıkı標記答案已被接受。所以,其他人很容易適應這一點。 – sandeepsure

0

嘗試

$json = '{"request_list":[{"id":"1","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null},{"id":"3","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null}]}'; 
    $data = json_decode($json); 

    $request = $data->request_list; 

    foreach($request as $request_data){ 
     echo $request_data->id; 
     echo $request_data->name; 
     echo $request_data->surname; 
    } 
1

使用此

$object = json_decode($json, true); 
$request_list = $object['request_list']; 
foreach($request_list as $r){ 
    echo $r['name']; 
    echo $r['blood_type']; 
    echo $r['phone_number']; 
}