开发者

PHP search for Key in multidimensional array

I have this:

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

        )

    [cary] => Array
           (
  开发者_StackOverflow社区         [no] => 64

           )
)

How can I find the key carx when i have the no=63 ? i know how to use array_search() but this one is a bit tricky. Like i can find key name id while I have 63 But this one is a bit tricky.

can someone help me ?


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


So you don't you your id key for the first level, so loop through and when you find a match stop looping and break out of the 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]);

Then you could use that key to get the whole nested array.


Is this of any use? I use it to do generic searches on arrays and objects. Note: It's not speed/stress tested. Feel free to point out any obvious problems.

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜