2010-11-19 158 views
1

嗨,大家好,我想知道如何基於ID返回索引以下。返回索引從JSON返回數組

$friends = '{ 
    "data": [ 
     { 
     "name": "Paul", 
     "id": "12000" 
     }, 
     { 
     "name": "Bonnie", 
     "id": "120310" 
     }, 
     { 
     "name": "Melissa", 
     "id": "120944" 
     }, 
     { 
     "name": "Simon", 
     "id": "125930" 
     }, 
     { 
     "name": "Anthony", 
     "id": "120605" 
     }, 
     { 
     "name": "David", 
     "id": "120733" 
    } 
    ] 
}'; 

$obj = json_decode($friends); 

例如,我想打印基於ID的名稱。我已經去使用array_search,但它不喜歡數組的結構。我將在sql循環中使用它,並從查詢中傳遞ID以從數組中返回名稱字符串。

print $obj->{'data'}[0]->{'name'}; 
//where 0 is returned index based on a defined ID. 

非常感謝

回答

0

您需要PHP 5.3,以便利用下面的關閉和加強三元運算符(打印名稱,如果找到記錄;否則,打印「沒有找到記錄。」):

$findById = function($id) use ($friends) { 
    foreach (json_decode($friends)->data as $friend) { 
    if ($friend->id === $id) return $friend->name; 
    } 
    return; 
}; 

echo $findById('125930') ?: 'No record found.'; 

好的事情是,你可以傳遞這個可調用對象,它會記住它的定義範圍。這意味着您可以傳遞任何ID,但$ friends數組始終可用於閉包。

0

json_decode使你的變量變成對象。要進行搜索,您可以使用:

// The extra true at the end makes it decode to associative arrays 
$json = json_decode($friends, true); 
findByName($json, 1234); 

function findNameById($obj, $id) { 
    foreach($obj as $o) { 
     if($o['id'] == $id) return $o['name']; 
    } 
    return false; 
}