PHP rename the keys of an array

前端 未结 4 1374
无人及你
无人及你 2021-01-12 15:36

How can I rename keys in an array?

Start with this array named $start_array,

[0] => 
      [date] => 2012-05-01
      [revenue] => 100
[1]          


        
相关标签:
4条回答
  • 2021-01-12 16:14

    Old name of the key of array is 'name' and new name is 'new_name'

    $myrow=array('name'=>'Sabuj'); 
    $myrow['new_name']=$myrow['name'];
    unset($myrow['name']);
    print_r($myrow);
    
    Result: Array ( [new_name] => 'Sabuj' )
    
    0 讨论(0)
  • 2021-01-12 16:19
    $new_keys = array( 'old1'=>'new1', 'old2'=>'new2', ... );
    foreach( $array as $key=>$value ) $newarray[$new_keys[$key]]=$value; 
    
    0 讨论(0)
  • 2021-01-12 16:36
    foreach( $start_array as &$arr ) {
      $arr["x"] = $arr['date'];
      unset( $arr['date'] );
      $arr['y'] = $arr['revenue'];
      unset( $arr['revenue'] );
    }
    unset($arr);
    

    Try the above code.

    0 讨论(0)
  • 2021-01-12 16:37

    You could use array_combine.

    $new_arr = array_map(function ($val) {
      return array_combine(array('x', 'y'), $val);
    }, $arr);
    

    The working demo.

    Or just ues a loop:

    foreach ($arr as &$el) {
      $el = array_combine(array('x', 'y'), $el);
    }
    
    0 讨论(0)
提交回复
热议问题