1

我只想通过使用值 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

4 回答 4

1
function getKey($arr,$value){
  foreach($arr as $key=>$element) {
    if($element["id_img"] == $value)
      return $key;
  }
  return false;
}
于 2013-07-13T23:03:28.740 回答
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()我使用仅获取数组中与我的规则匹配的项目(如闭包的 return 语句中定义的)而不是循环。$result因为我知道我只有一个值为 17 的 ID,所以我知道我最终将在数组中只有一项。然后我从数组键( using )中检索第一个元素array_keys( $result )[0]- 这是在原始数组中保存 id_img = 17 的键。

于 2013-07-13T23:26:11.243 回答
0
<?php
$found=false;
$searched=17;
foreach($array_test as $k=>$data)
 if($data['id_img']==$searched)
   $found=$key;

如果没有找到,您的密钥在$found var 或 false

于 2013-07-13T23:01:32.923 回答
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;
于 2013-07-13T23:12:15.030 回答