多维数组函数的 key() 返回 0

  • 本文关键字:返回 key 数组 函数 php
  • 更新时间 :
  • 英文 :


我构建了一个函数来仅搜索多维数组中的特定键(不要与搜索每个元素的in_arrayarray_search混淆。我正在尝试返回具有匹配项的多维数组中子数组的键。

$array = array(array("hello1", "hello2"), array("test1", "test2"));
function search_custom($needle, $specific_key) {
    global $array;
    foreach($array as $value) {
        /* only searches specific key in the sub-arrays */
        if($needle == $value[$specific_key]) {
            return key($value); /* should return 1? */
        }
    }
}
print_r(search_custom("test2", 1)); /* search only in element 1 of sub-arrays */

不幸的是,这输出"0",即使"test2"在多数组的元素 1 中。

你对key()的使用是错误的,它需要一个数组。但是foreach可以给你钥匙,你不必寻找它:

$array = array(array("hello1", "hello2"), array("test1", "test2"));
function search_custom($needle, $specific_key) {
    global $array;
    foreach($array as $key=>$value) {
        /* only searches specific key in the sub-arrays */
        if($needle == $value[$specific_key]) {
            return $key;
        }
    }
}
print_r(search_custom("test2", 1)); /* search only in element 1 of sub-arrays */

最新更新