PHP rename the keys of an array
Asked Answered
G

6

8

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'] );
}
Garrek answered 24/9, 2012 at 23:45 Comment(6)
wouldn't creating it with the key names you want in the first place be a better idea?Stephaniestephannie
Unfortunately that isn't possible, I'm given this array.Garrek
Someone else's code generates the array, and I shouldn't change that code.Garrek
And what might be your loss in using the old keys?Thwack
Can you provide the result of a var_dump($final_array) ? I dont see anything wrong in your code assuming that the original keys you want to change are dateid and ctrl_version_revenuePeriotic
@HernanVelasquez yeah my code works correctly, just wanted to know of a cleaner way.Garrek
T
7
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.

Thwack answered 24/9, 2012 at 23:50 Comment(0)
G
3

You could use array_combine.

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

The working demo.

Or just use a loop:

foreach ($arr as &$el) {
  $el = array_combine(array('x', 'y'), $el);
}
Gabey answered 25/9, 2012 at 2:50 Comment(0)
R
1

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' )
Razzledazzle answered 2/8, 2017 at 5:26 Comment(0)
H
0
$new_keys = array( 'old1'=>'new1', 'old2'=>'new2', ... );
foreach( $array as $key=>$value ) $newarray[$new_keys[$key]]=$value; 
Hardtack answered 25/9, 2012 at 2:55 Comment(1)
Your answer would be clearer if it included more than just the code itself.Iulus
S
0

I like this most performant loop solution with an array_combine, which is also very readable.

$data = [
    ['date' => '2012-05-01', 'revenue' => '100'],
    ['date' => '2012-05-02', 'revenue' => '200'],
];

$array_map = [];
foreach ($data as $key => $values) {
    $array_map[$key] = array_combine(['x', 'y'], $values);
}

Output:

[0] => 
      [x] => 2012-05-01
      [y] => 100
[1] =>
      [x] => 2012-05-02
      [y] => 200
Seize answered 18/9, 2022 at 20:36 Comment(0)
D
-1

You can do it without any loop

Like below

$arr= str_replace("date", "x", json_encode($arr));  
$arr= json_decode($arr, true);

$arr= str_replace("revenue", "y", json_encode($arr));  
$arr= json_decode($arr, true);

Note : Make sure you don't have any value the same as the key name. In this type of case, your value will also change. very rare case it happens

Dynasty answered 3/3, 2022 at 5:51 Comment(7)
This technique is not stable for general use because it risks replacing values as well as keys.Pentamerous
@Pentamerous you are right but in the above case it's not a riskDynasty
For the provided sample case, I agree there is no risk. However, researchers who do not understand the risks of this technique may fall prey to damaging their data payload. This answer is missing its educational explanation. Explaining the vulnerability of this answer seems pertinent.Pentamerous
@Pentamerous I have added note ,ThanksDynasty
It is not enough to check for values that are the same as the targeted keys. It is also problematic if the targeted key(s) might exist anywhere in the json string. If one key is a substring of another key or value, then again, this technique will mutilate the json string. I simply would never recommend this technique in any professional (or unprofessional) project.Pentamerous
Yeah, But this is the perfect solution for the above question, there are never keys and values are the sameDynasty
I will not call this a "perfect" solution, I'll grant you "it works" on the supplied data. The researchers that hit this page WILL NOT have the exact same data as the asker. When we use this page to close future duplicates, those questions WILL NOT have the exact same data as this asker. It is important to prioritize the researcher experience when posting answers. There are also the fringe cases where the values or their types will be altered by json_ functions native behavior.Pentamerous

© 2022 - 2025 — McMap. All rights reserved.