繁体   English   中英

PHP在多维数组中搜索Key

[英]PHP search for Key in multidimensional array

我有这个:

Array
(
    [carx] => Array
        (
            [no] => 63

        )

    [cary] => Array
           (
           [no] => 64

           )
)

当我的编号为63时,如何找到钥匙钥匙? 我知道如何使用array_search()但是这个有点棘手。 就像我在63时候可以找到键名id ,但是这个有点棘手。

有人能帮我吗 ?

foreach ($array as $i => $v) $array[$i] = $v['no'];
$key = array_search(63, $array);

因此,您不需要第一层的ID密钥,因此可以遍历并找到匹配项时停止循环并退出foreach

$id = 0;
$needle = 63;
foreach($array as $i => $v)
{
    if ($v['no'] == $needle)
    {
        $id = $i;
        break 1;
    }
}
// do what like with any other nested parts now
print_r($array[$id]);

然后,您可以使用该键来获取整个嵌套数组。

这有用吗? 我用它对数组和对象进行通用搜索。 注意:未经速度/压力测试。 随时指出任何明显的问题。

function arrayKeySearch(array $haystack, string $search_key, &$output_value, int $occurence = 1){
    $result             = false;
    $search_occurences  = 0;
    $output_value       = null;
    if($occurence < 1){ $occurence = 1; }
    foreach($haystack as $key => $value){
        if($key == $search_key){
            $search_occurences++;
            if($search_occurences == $occurence){
                $result         = true;
                $output_value = $value;
                break;
            }
        }else if(is_array($value) || is_object($value)){
            if(is_object($value)){
                $value = (array)$value;
            }
            $result = arrayKeySearch($value, $search_key, $output_value, $occurence);
            if($result){
                break;
            }
        }
    }
    return $result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM