PHP重命名数组的键

时间:2021-08-13 10:45:42

How can I rename keys in an array?

如何在数组中重命名键?

Start with this array named $start_array,

从这个名为$start_array的数组开始,

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

and change the keys for 'date' and 'revenue' so you get this $final_array:

改变" date "和" revenue "的键值你得到$final_array

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

Here is my terrible attempt which works but is messy.

这是我的一次可怕的尝试,它很有效,但也很混乱。

$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 个解决方案

#1


6  

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.

上面的代码。

#2


1  

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);
}

#3


0  

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

#4


0  

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

数组键的旧名是“name”,新名是“new_name”

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

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

#1


6  

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.

上面的代码。

#2


1  

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);
}

#3


0  

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

#4


0  

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

数组键的旧名是“name”,新名是“new_name”

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

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