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

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

    Here is solution:

    <?php
    $students['e1003']['birthplace'] = ("Mandaluyong <br>");
    $students['ter1003']['birthplace'] = ("San Juan <br>");
    $students['fgg1003']['birthplace'] = ("Quezon City <br>");
    $students['bdf1003']['birthplace'] = ("Manila <br>");
    
    $key = array_search('Delata Jona', array_column($students, 'name'));
    echo $key;  
    
    ?>
    
    0 讨论(0)
  • 2020-11-22 00:58
    function findKey($tab, $key){
        foreach($tab as $k => $value){ 
            if($k==$key) return $value; 
            if(is_array($value)){ 
                $find = findKey($value, $key);
                if($find) return $find;
            }
        }
        return null;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题