我只想通过搜索值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"),
);
谢谢你的帮助。
function getKey($arr,$value){
foreach($arr as $key=>$element) {
if($element["id_img"] == $value)
return $key;
}
return false;
}
纯粹出于个人喜好,我喜欢在没有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的键。
<?php
$found=false;
$searched=17;
foreach($array_test as $k=>$data)
if($data['id_img']==$searched)
$found=$key;
您的密钥在$foundvar中,如果未找到,则为false
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;