简体   繁体   中英

recursive array_key_search function PhP

Having this recursive function ( $key can be numeric as array(0=>'value1',1=>'value2' or string as array('key1'=>'value1','key2'=>'value2') ), being $key , needle and $array haystack:

 public function array_key_search($searched_key, $array = array()){

         * @param   $searched_key: Key to search.
         *          $array: Array with keys to check.
         * Recursive method to check if a key exists in a multidemensional array. 
         * If key exists, it returns corresponding value.
         */

        foreach($array as $key => $value){
            $key = "$key";
            if($key_value == false){
                if($key == $searched_key){
                    return $value;
                }else{
                    if(is_array($value)){
                        $key_value = self::array_key_search($searched_key, $value);
                    }
                }
            }
        }
        $key_value == is_null($key_value) ? false : $key_value;

        return $key_value;
    }

May I use if($key === $searched_key) instead of invoking my $key param as string for comparision?

This time I'm talking about performance because this function may be hard to process sometimes.

This does what you want

$arr = [
  'key1' => [
    'key1.1' => [
      'key1.1.1' => 'key1.1.1',
      'key1.1.2' => 'key1.1.2'
    ],
    'key1.2' => [
      'key1.2.1' => 'key1.2.1',
      'key1.2.2' => 'key1.2.2'
    ],
  ],
  'key2' => [
    'key2.1' => [
      'key2.1.1' => 'key2.1.1',
      'key2.1.2' => 'key2.1.2'
    ]
  ]
];

function get_key_val($search_key, $arr){
  foreach($arr as $key => $value){
    if( is_array($value) ){
      $result = get_key_val($search_key, $value);
      if ($result){
        return $result;
      }
    }else{
      if ($search_key == $key){
       return $value;
      }
    }
  }
  return null;
}

var_dump(get_key_val('key2.1.2', $arr));

RETURNS

string(8) "key2.1.2"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM