How to search by key=>value in a multidimensional array in PHP

前端 未结 15 2314
闹比i
闹比i 2020-11-22 00:13

Is there any fast way to get all subarrays where a key value pair was found in a multidimensional array? I can\'t say how deep the array will be.

Simple example arra

15条回答
  •  耶瑟儿~
    2020-11-22 00:44

    This is a revised function from the one that John K. posted... I need to grab only the specific key in the array and nothing above it.

    function search_array ( $array, $key, $value )
    {
        $results = array();
    
        if ( is_array($array) )
        {
            if ( $array[$key] == $value )
            {
                $results[] = $array;
            } else {
                foreach ($array as $subarray) 
                    $results = array_merge( $results, $this->search_array($subarray, $key, $value) );
            }
        }
    
        return $results;
    }
    
    $arr = array(0 => array(id=>1,name=>"cat 1"),
           1 => array(id=>2,name=>"cat 2"),
           2 => array(id=>3,name=>"cat 1"));
    
    print_r(search_array($arr, 'name', 'cat 1'));
    

提交回复
热议问题