2010-11-19 155 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; 
}