php Checking if value exists in array of array

前端 未结 3 1754
孤城傲影
孤城傲影 2021-01-02 15:52

I have an array within an array.

$a = array ( 0 => array ( \'value\' => \'America\', ), 1 => array ( \'value\' => \'England\', ), )
3条回答
  •  渐次进展
    2021-01-02 16:04

    A general solution would be:

    function deep_in_array($needle, $haystack) {
        if(in_array($needle, $haystack)) {
            return true;
        }
        foreach($haystack as $element) {
            if(is_array($element) && deep_in_array($needle, $element))
                return true;
        }
        return false;
    }
    

    The reason why I chose to use in_array and a loop is: Before I examine deeper levels of the array structure, I make sure, that the searched value is not in the current level. This way, I hope the code to be faster than doing some kind of depth-first search method.


    Of course if your array is always 2 dimensional and you only want to search in this kind of arrays, then this is faster:

    function in_2d_array($needle, $haystack) {
        foreach($haystack as $element) {
            if(in_array($needle, $element))
                return true;
        }
        return false;
    }
    

提交回复
热议问题