从JSON返回的索引返回索引

时间:2010-11-19 00:44:04

标签: php arrays

大家好,我很想知道如何根据ID返回索引。

$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.

非常感谢

2 个答案:

答案 0 :(得分: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数组将始终可用于闭包。

答案 1 :(得分: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;
}