tags:

views:

306

answers:

3

In an array such as the one below, how could I rename "fee_id" to "id"?

Array
(
    [0] => Array
        (
            [fee_id] => 15
            [fee_amount] => 308.5
            [year] => 2009                
        )

    [1] => Array
        (
            [fee_id] => 14
            [fee_amount] => 308.5
            [year] => 2009

        )

)
+1  A: 

Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?

foreach ($array as $arr)
{
  $arr['id'] = $arr['fee_id'];
  unset($arr['fee_id']);
}

There is no function builtin doing such thin afaik.

TheGrandWazoo
VolkerK
This does not work, the PHP manual says: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself
Niels Bom
Ah, thanks for the update. Didn't realise it :-).
TheGrandWazoo
+3  A: 
foreach ( $array as $k=>$v )
{
  $array[$k] ['id'] = $array[$k] ['fee_id'];
  unset($array[$k]['fee_id']);
}

This should work

lamas
You probably want to make it `foreach( array_keys($array) as $k)` or `foreach($array as $k=>$v)`
gnarf
Thanks, I forgot the =>$v
lamas
A: 
$arrayNum = count($theArray);

for( $i = 0 ; $i < $arrayNum ; $i++ )
{
    $fee_id_value = $theArray[$i]['fee_id'];
    unset($theArray[$i]['fee_id']);
    $theArray[$i]['id'] = $fee_id_value;
}

This should work.

Niels Bom
$i < count($theArray) - bad code
lamas
Because it re-counts it every time?
Niels Bom
Yep, assuming he has a big array this will count it every time and the page will load slower / the server load will go up
lamas
Updated the code.
Niels Bom