replace array keys with given respective keys

前端 未结 10 1422
轻奢々
轻奢々 2020-12-29 09:16

I have an array like below

$old = array(
       \'a\' => \'blah\',
       \'b\' => \'key\',
       \'c\' => \'amazing\',
       \'d\' => array(
          


        
10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-29 09:45

    I just solved this same problem in my own application, but for my application $keyReplaceInfoz acts like the whitelist- if a key is not found, that whole element is removed from the resulting array, while the matching whitelisted keys get translated to the new values.

    I suppose you could apply this same algorithm maybe with less total code by clever usage of array_map (http://php.net/manual/en/function.array-map.php), which perhaps another generous reader will do.

    function filterOldToAllowedNew($key_to_test){       
        return isset($keyReplaceInfoz[$key_to_test])?$keyReplaceInfoz[$key_to_test]:false;
    }   
    
    $newArray = array();
    
    foreach($old as $key => $value){
        $newkey = filterOldToAllowedNew($key);
        if($newkey){
           $newArray[$newkey] = $value;
        }
    }
    
    print_r($newArray);
    

提交回复
热议问题