phparraysmultidimensional-arraykey

Rename key in each row of a 2d array


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

Input array:

[
    ['fee_id' => 15, 'fee_amount' => 308.5, 'year' => 2009],
    ['fee_id' => 14, 'fee_amount' => 308.5, 'year' => 2009],
]

Expected result:

[
    ['id' => 15, 'fee_amount' => 308.5, 'year' => 2009],
    ['id' => 14, 'fee_amount' => 308.5, 'year' => 2009],
]

Solution

  • foreach ( $array as $k=>$v )
    {
      $array[$k] ['id'] = $array[$k] ['fee_id'];
      unset($array[$k]['fee_id']);
    }
    

    This should work