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

前端 未结 15 2045
闹比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条回答
  •  -上瘾入骨i
    2020-11-22 01:00

    And another version that returns the key value from the array element in which the value is found (no recursion, optimized for speed):

    // if the array is 
    $arr['apples'] = array('id' => 1);
    $arr['oranges'] = array('id' => 2);
    
    //then 
    print_r(search_array($arr, 'id', 2);
    // returns Array ( [oranges] => Array ( [id] => 2 ) ) 
    // instead of Array ( [0] => Array ( [id] => 2 ) )
    
    // search array for specific key = value
    function search_array($array, $key, $value) {
      $return = array();   
      foreach ($array as $k=>$subarray){  
        if (isset($subarray[$key]) && $subarray[$key] == $value) {
          $return[$k] = $subarray;
          return $return;
        } 
      }
    }
    

    Thanks to all who posted here.

提交回复
热议问题