我有这样PHP:获得多维数组中的密钥?
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
)
数组我如何能得到通过提供价值的关键?
例如如果我搜索“水牛”,array_search可能会返回“2”。
感谢
我有这样PHP:获得多维数组中的密钥?
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
)
数组我如何能得到通过提供价值的关键?
例如如果我搜索“水牛”,array_search可能会返回“2”。
感谢
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
);
function findInArray($term, $array) {
foreach($array as $key => $val) {
if(in_array($term, $val, true)) {
return $key;
}
}
}
echo findInArray('buffaloes', $myArray); // 2
echo findInArray(78, $myArray); // 2
function asearch($key, $myArray) {
for ($i = 0; $i < sizeof($myArray); $i++) {
if ($myArray[$i][0] == $key) {
return $i;
}
}
return -1; # no match
}
虽然,你可能会想你的阵列重组到:
$myarray = array(
'dogs' => 98,
'cats' => 56,
'buffaloes' => 78
);
而只是做:
$myArray['buffaloes']; # 78
你能做到这一点的唯一方法是迭代每个项目,并预成形一个Linear Search
$i = -1;
foreach ($myArray as $key => $item){
if ($item[0] == 'buffaloes'){
$i = $key;
break;
}
}
//$i now holds the key, or -1 if it doesn't exist
正如你所看到的,它真的非常低效,就好像你的数组有20,000个项目,'水牛'是最后一个项目,你必须进行20,000次比较。
换句话说,您需要重新设计您的数据结构,以便您可以使用该键查找某些内容,例如,更好的方法可能是重新排列阵列,以便将搜索的字符串作为关键字,例如:
$myArray['buffaloes'] = 76;
这是更快得多,因为它使用一个更好的数据结构,使得它只有至多n log n
比较(其中,n是阵列中的项目数)。这是因为数组实际上是一个有序的映射。
另一种选择,如果你知道你正在寻找价值的精确值是使用array_search
是的,你是对的。 :) – baltoro 2009-12-19 19:42:02
您可以遍历数组中的每个元素,测试如果每个条目的第一个元素是等于“水牛”。
例如:
foreach ($myArray as $key => $value) {
if ($value[0] == "buffaloes") {
echo "The key is : $key";
}
}
会得到你:
The key is : 2
另一个想法,如果你想整个入境,可能与array_filter
工作(更可笑吗?)以及为“bufalloes”条目返回true的回调函数:
function my_func($val) {
return $val[0] == "buffaloes";
}
$element = array_filter($myArray, 'my_func');
var_dump($element);
会得到你:
array
2 =>
array
0 => string 'buffaloes' (length=9)
1 => int 78
而且
var_dump(key($element));
Gves你你想要的2
。
我从来没有听说过内置函数。如果你想要更通用的东西,那么你需要编写你自己的函数并使用递归。也许array_walk_recursive会有帮助
你可能做错了什么... – 2009-12-19 19:31:46
你在Yacoby回答说,除非你有重要的理由保持你的数据,你应该重新设计它。 – 2009-12-19 19:42:42
你没事。我承认。但是,是的,实际上有一个特定的情况,我需要这样的结构,并且该阵列中的项目数不超过10个,因此从性能和效率的角度来看,对我来说这很好。 – baltoro 2009-12-19 21:04:26