如何通过知道数组的值来获得数组中的密钥?例如,这里是一个数组:通过值获取数组中的密钥
$array = Array("Item1" => array("Number" => "One", "Letter" => "A"));
只要知道“一”或“A”,我怎么能得到主键名,Item1
?
我已经看过array_key_value
和in_array
但我不认为这些函数对我的类型数组有帮助。
如何通过知道数组的值来获得数组中的密钥?例如,这里是一个数组:通过值获取数组中的密钥
$array = Array("Item1" => array("Number" => "One", "Letter" => "A"));
只要知道“一”或“A”,我怎么能得到主键名,Item1
?
我已经看过array_key_value
和in_array
但我不认为这些函数对我的类型数组有帮助。
由于它是一个2d数组,因此您需要在内部数组中搜索该值,因此您必须创建自己的函数来执行此操作。事情是这样的:
function findInArray($array, $lookup){
//loop over the outer array getting each key and value.
foreach($array as $key=>$value){
//if we found our lookup value in the inner array
if(in_array($lookup, $value)){
//return the original key
return $key;
}
}
//else, return null because not found
return null;
}
$array = Array("Item1" => array("Number" => "One", "Letter" => "A"));
var_dump(findInArray($array, 'One')); //outputs string(5) "Item1"
var_dump(findInArray($array, 'Two')); //outputs null
此功能可以帮助你
function key_of_value($array, $value){
foreach($array as $key=>$val){
if(in_array($value, $val)){
return $key;
}
}
return null;
}
echo key_of_value(['Item1'=>['One','Two','Three','Hello',2,6]],'A');
没有办法通过数据迭代左右。这可能是有点更优雅两个以上foreach
循环:
<?php
$match = null;
$needle = 'Two';
$haystack = [
'Item1' => [
'Number' => 'One',
'Letter' => 'A'
],
'Item2' => [
'Number' => 'Two',
'Letter' => 'B'
],
'Item3' => [
'Number' => 'Three',
'Letter' => 'C'
],
];
array_walk($haystack, function($entry, $key) use ($needle, &$match) {
if(in_array($needle, $entry)) {
$match = $key;
}
});
var_dump($match);
输出显然是:
string(5) "Item2"
您可以使用array_walk_recursive
,反覆数组值递归。我写了一个函数,它返回嵌套数组中的搜索值的主键。
<?php
$array = array("Item1" => array("Number" => "One", "Letter" => "A", 'other' => array('Number' => "Two")));
echo find_main_key($array, 'One'); //Output: "Item1"
echo find_main_key($array, 'A'); //Output: "Item1"
echo find_main_key($array, 'Two'); //Output: "Item1"
var_dump(find_main_key($array, 'nothing')); // NULL
function find_main_key($array, $value) {
$finded_key = NULL;
foreach($array as $this_main_key => $array_item) {
if(!$finded_key) {
array_walk_recursive($array_item, function($inner_item, $inner_key) use ($value, $this_main_key, &$finded_key){
if($inner_item === $value) {
$finded_key = $this_main_key;
return;
}
});
}
}
return $finded_key;
}
这是我会怎么做:
foreach($array as $key => $value) { if(in_array('One', $value)) echo $key; }
以'foreach' –