PHP search for Key in multidimensional array

前端 未结 3 841
花落未央
花落未央 2020-12-12 06:29

I have this:

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

        )

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

            


        
相关标签:
3条回答
  • 2020-12-12 07:15

    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.

    0 讨论(0)
  • 2020-12-12 07:18

    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 讨论(0)
  • 2020-12-12 07:31
    foreach ($array as $i => $v) $array[$i] = $v['no'];
    $key = array_search(63, $array);
    
    0 讨论(0)
提交回复
热议问题