Don P
Don P

Reputation: 63627

Rename the keys of children in a 2-dimensional array

Starting with this array

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

How can I rename the keys date and revenue in the child arrays so I get this:

$final_array = [
    ["x" => "2012-05-01", "y" => 100],
    ["x" => "2012-05-02", "y" => 200],
];

Here is my attempt which works, but is messy:

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

Upvotes: 8

Views: 19428

Answers (6)

xdazz
xdazz

Reputation: 160833

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

Upvotes: 3

Bhargav Variya
Bhargav Variya

Reputation: 765

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

Upvotes: -1

lordisp
lordisp

Reputation: 730

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

Upvotes: 0

ranojan
ranojan

Reputation: 837

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' )

Upvotes: 1

OneThreeSeven
OneThreeSeven

Reputation: 422

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

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80639

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.

Upvotes: 7

Related Questions