replace array keys with given respective keys

前端 未结 10 1332
轻奢々
轻奢々 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:43

    This question is old but since it comes up first on Google I thought I'd add solution.

    // Subject
    $old = array('foo' => 1, 'baz' => 2, 'bar' => 3));
    
    // Translations    
    $tr  = array('foo'=>'FOO', 'bar'=>'BAR');
    
    // Get result
    $new = array_combine(preg_replace(array_map(function($s){return "/^$s$/";}, 
               array_keys($tr)),$tr, array_keys($old)), $old);
    
    // Output
    print_r($new);
    

    Result:

        
        Array
        (
           [FOO] => 1
           [baz] => 2
           [BAR] => 3
        )
    

提交回复
热议问题