Php - 按键从数组中选择项目

时间:2014-05-26 13:08:10

标签: php arrays key

我有这个PHP数组:

Array ( [0] => Array ( [id] => 64 [img] => 20090refe61fr705-est-Ue3hM [rank] => 1 )
[1] => Array ( [id] => 64 [img] => 200frferf612fr05-stanze-kQakO [rank] => 2 ) 
[2] => Array ( [id] => 64 [img] => 20090306123705-stanze-zgYg9 [rank] => 3 ) 
[3] => Array ( [id] => 981 [img] => 200923rfrtggr4515-est-2SpjN [rank] => 1 ) 

我想,在一个循环中打印一个项目[img],其中[id]等于981(例如)

我该怎么办?

1 个答案:

答案 0 :(得分:1)

  

我想,在一个循环中打印一个项目[img],其中[id]等于981(例如)

如果您想搜索示例数组中的特定id并返回匹配的img。不需要array_search。一个好的'foreach就足够了。

考虑这个例子:

$values = array( array('id' => 64, 'img' => '20090refe61fr705-est-Ue3hM', 'rank' => 1), array('id' => 64, 'img' => '200frferf612fr05-stanze-kQakO', 'rank' => 2), array('id' => 64, 'img' => '20090306123705-stanze-zgYg9', 'rank' => 3), array('id' => 981, 'img' => '200923rfrtggr4515-est-2SpjN', 'rank' => 1),);

$needle = 981;
$search_results = array();
foreach($values as $key => $value) {
    if($needle == $value['id']) {
        $search_results[] = $value['img'];
        // or echo $value['img'];
    }
}

echo '<pre>';
print_r($search_results);
echo '</pre>';

Sample Fiddle