Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP rename the keys of an array

How can I rename keys in an array?

Start with this array named $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:

[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'] );
}
like image 539
Don P Avatar asked Sep 24 '12 23:09

Don P


2 Answers

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.

like image 170
hjpotter92 Avatar answered Oct 08 '22 07:10

hjpotter92


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);
}
like image 37
xdazz Avatar answered Oct 08 '22 05:10

xdazz