Check if a specific value exists at a specific key in any subarray of a multidimensional array

前端 未结 13 2207
梦毁少年i
梦毁少年i 2020-11-27 18:42

I need to search a multidimensional array for a specific value in any of the indexed subarrays.

In other words, I need to check a single column of the multidimension

13条回答
  •  再見小時候
    2020-11-27 19:08

    I wrote the following function in order to determine if an multidimensional array partially contains a certain value.

    function findKeyValue ($array, $needle, $value, $found = false){
        foreach ($array as $key => $item){
            // Navigate through the array completely.
            if (is_array($item)){
                $found = $this->findKeyValue($item, $needle, $value, $found);
            }
    
            // If the item is a node, verify if the value of the node contains
            // the given search parameter. E.G.: 'value' <=> 'This contains the value'
            if ( ! empty($key) && $key == $needle && strpos($item, $value) !== false){
                return true;
            }
        }
    
        return $found;
    }
    

    Call the function like this:

    $this->findKeyValue($array, $key, $value);
    

提交回复
热议问题