如何通过在php数组中搜索特定值来获取密钥

时间:2013-07-13 22:58:29

标签: php arrays

我只想通过使用值id_img = 17进行搜索来获取密钥。 这是数组:

$array_test = array (
0  => array("id_img" => 18, "desciption" => "Super image", "author" => "Person 1"),
1  => array("id_img" => 17, "desciption" => "Another image", "author" => "Person 2"),
2  => array("id_img" => 22, "desciption" => "The last image", "author" => "John Doe"),
);

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

function getKey($arr,$value){
  foreach($arr as $key=>$element) {
    if($element["id_img"] == $value)
      return $key;
  }
  return false;
}

答案 1 :(得分:1)

我喜欢在没有foreach或for循环的情况下做一些事情,这纯粹是出于个人偏好。

这是我的目的:

$array_test = array (
    0  => array("id_img" => 18, "desciption" => "Super image", "author" => "Person 1"),
    1  => array("id_img" => 17, "desciption" => "Another image", "author" => "Person 2"),
    2  => array("id_img" => 22, "desciption" => "The last image", "author" => "John Doe"),
);

$result = array_filter( $array_test, function( $value )
{
    return $value['id_img'] == 17 ? true : false;
});
$key = array_keys( $result )[0];

print_r( $key );

我使用array_filter()而不是循环来获取数组中与我的规则匹配的那些项(如Closure的return语句中所定义)。因为我知道我只有一个值为17的ID,所以我知道$result数组中只有一个项目。然后我从数组键中检索第一个元素(使用array_keys( $result )[0]) - 这是在原始数组中保存id_img = 17的键。

答案 2 :(得分:0)

<?php
$found=false;
$searched=17;
foreach($array_test as $k=>$data)
 if($data['id_img']==$searched)
   $found=$key;

你的密钥是 $ found var或false如果找不到

答案 3 :(得分:0)

Try:

$array_test = array (
0  => array("id_img" => 18, "desciption" => "Super image", "author" => "Person 1"),
1  => array("id_img" => 17, "desciption" => "Another image", "author" => "Person 2"),
2  => array("id_img" => 22, "desciption" => "The last image", "author" => "John Doe"),
);

$result = null;

foreach($array_test as $key => $val )
{
  if( $val['id_img'] == 17 )
    $result = $key;

}
return $result;