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

前端 未结 15 2086
闹比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:41

    If you want to search for array of keys this is good

    function searchKeysInMultiDimensionalArray($array, $keys)
    {
        $results = array();
    
        if (is_array($array)) {
            $resultArray = array_intersect_key($array, array_flip($keys));
            if (!empty($resultArray)) {
                $results[] = $resultArray;
            }
    
            foreach ($array as $subarray) {
                $results = array_merge($results, searchKeysInMultiDimensionalArray($subarray, $keys));
            }
        }
    
        return $results;
    }
    

    Keys will not overwrite because each set of key => values will be in separate array in resulting array.
    If you don't want duplicate keys then use this one

    function searchKeysInMultiDimensionalArray($array, $keys)
    {
        $results = array();
    
        if (is_array($array)) {
            $resultArray = array_intersect_key($array, array_flip($keys));
            if (!empty($resultArray)) {
                foreach($resultArray as $key => $single) {
    
                    $results[$key] = $single;
                }
            }
    
            foreach ($array as $subarray) {
                $results = array_merge($results, searchKeysInMultiDimensionalArray($subarray, $keys));
            }
        }
    
        return $results;
    }
    

提交回复
热议问题