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

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

    Came back to post this update for anyone needing an optimisation tip on these answers, particulary John Kugelman's great answer up above.

    His posted function work fine but I had to optimize this scenario for handling a 12 000 row resultset. The function was taking an eternal 8 secs to go through all records, waaaaaay too long.

    I simply needed the function to STOP searching and return when match was found. Ie, if searching for a customer_id, we know we only have one in the resultset and once we find the customer_id in the multidimensional array, we want to return.

    Here is the speed-optimised ( and much simplified ) version of this function, for anyone in need. Unlike other version, it can only handle only one depth of array, does not recurse and does away with merging multiple results.

    // search array for specific key = value
    public function searchSubArray(Array $array, $key, $value) {   
        foreach ($array as $subarray){  
            if (isset($subarray[$key]) && $subarray[$key] == $value)
              return $subarray;       
        } 
    }
    

    This brought down the the task to match the 12 000 records to a 1.5 secs. Still very costly but much more reasonable.

提交回复
热议问题