replace array keys with given respective keys

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

    This works irrespective of array order & array count. Output order & value will be based on replaceKey.

    $replaceKey = array('a' => 'newA', 'b' => 'newB', 'c' => 'newC', 'd' => 'newD', 'e' => 'newE','f'=>'newF');
    
    $array = array(
           'a' => 'blah',
           'd' => array(
                    0 => 'want to replace',
                    1 => 'yes I want to'
                  ),
           'noKey'=>'RESIDUAL',
           'c' => 'amazing',
           'b' => 'key',
           );
    
    $filterKey = array_intersect_key($replaceKey,$array);
    $filterarray = array_intersect_key(array_merge($filterKey,$array),$filterKey);
    
    $replaced = array_combine($filterKey,$filterarray);
    
    //output
    var_export($replaced);
    //array ( 'newA' => 'blah', 'newB' => 'key', 'newC' => 'amazing', 'newD' => array ( 0 => 'want to replace', 1 => 'yes I want to' ) )
    
    0 讨论(0)
  • 2020-12-29 10:02
        <?php
    $new = array(); 
    
    foreach ($old as $key => $value)
    {
         $new[$keyReplaceInfoz][$key] = $value;
    
    }
    ?>
    
    0 讨论(0)
  • 2020-12-29 10:07

    IMO using array_combine, array_merge, even array_intersect_key is overkill. The original code is good enough, and very fast.

    0 讨论(0)
  • 2020-12-29 10:09
    <?php
    $old = array(
           'a' => 'blah',
           'b' => 'key',
           'c' => 'amazing',
           'd' => array(
                    0 => 'want to replace',
                    1 => 'yes I want to'
                  )
           );
    $keyReplaceInfoz = array('a' => 'newA', 'b' => 'newB', 'c' => 'newC', 'd' => 'newD');
    
    $new = array(); 
    
    foreach ($old as $key => $value)
    {
        $newvalue =  $keyReplaceInfoz[$key];
       $new[$key] = $newvalue;
    }
    print_r($new);
    
    ?>
    
    0 讨论(0)
提交回复
热议问题