PHP重命名数组的键

时间:2012-09-24 23:45:13

标签: php arrays key key-value

如何重命名数组中的键?

从这个名为$ start_array,

的数组开始
[0] => 
      [date] => 2012-05-01
      [revenue] => 100
[1] =>
      [date] => 2012-05-02
      [revenue] => 200

并更改'date'和'revenue'的键,以便获得$ final_array:

[0] => 
      [x] => 2012-05-01
      [y] => 100
[1] =>
      [x] => 2012-05-02
      [y] => 200

这是我可怕的尝试,但是很麻烦。

$final_array = array();
$max = count($start_array);
for ($j = 0; $j < $max; $j++) {
  $final_array[] = array('x' => $start_array[$j]['dateid'], 'y' => $start_array[$j]['ctrl_version_revenue'] );
}

4 个答案:

答案 0 :(得分:6)

foreach( $start_array as &$arr ) {
  $arr["x"] = $arr['date'];
  unset( $arr['date'] );
  $arr['y'] = $arr['revenue'];
  unset( $arr['revenue'] );
}
unset($arr);

试试上面的代码。

答案 1 :(得分:1)

您可以使用array_combine

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

The working demo.

或者只是一个循环:

foreach ($arr as &$el) {
  $el = array_combine(array('x', 'y'), $el);
}

答案 2 :(得分:0)

$new_keys = array( 'old1'=>'new1', 'old2'=>'new2', ... );
foreach( $array as $key=>$value ) $newarray[$new_keys[$key]]=$value; 

答案 3 :(得分:0)

数组键的旧名称是&#39; name&#39;新名称是&#39; new_name&#39;

$myrow=array('name'=>'Sabuj'); 
$myrow['new_name']=$myrow['name'];
unset($myrow['name']);
print_r($myrow);

Result: Array ( [new_name] => 'Sabuj' )