4

Possible Duplicate:
In PHP, how do you change the key of an array element?

This the array

Array
(
    [0] => Array
        (
            [id] => 1
            [due_date] => 2011-09-23
            [due_amount] => 10600.00
        )

    [1] => Array
        (
            [id] => 2
            [due_date] => 2011-10-23
            [due_amount] => 10600.00
        )

    [2] => Array
        (
            [id] => 3
            [due_date] => 2011-11-23
            [due_amount] => 10600.00
        )
)

how to change id to u_id in this array?

Regards

Community
  • 1
  • 1
Gihan Lasita
  • 2,955
  • 13
  • 48
  • 65
  • What have you tried so far so it saves our time trying what you have already tried? – RSM Aug 24 '11 at 19:37

2 Answers2

6
array_walk_recursive($array, 'changeIDkey');

function changeIDkey($item, &$key)
{
    if ($key == 'id') $key = 'u_id';
}

PHP Manual: array_walk_recursive

EDIT

This will not work for the reason @salathe gave in the Comments below. Working on alternative.

ACTUAL ANSWER

function changeIDkey(&$value,$key)
{
    if ($value === "id") $value = "u_id";
}

$new = array();
foreach ($array as $key => $value)
{
    $keys = array_keys($value);
    array_walk($keys,"changeIDkey");
    $new[] = array_combine($keys,array_values($value));
}

var_dump($new); //verify

Where $array is your input array. Note that this will only work with your current array structure (two-dimensions, changes keys on only second dimension).

The loop iterates through the inner arrays changing "id" to "u_id" in the keys and then recombines the new keys with the old values.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • Take heed of the note on the `array_walk()` manual page, which is just as applicable for `array_walk_recursive()`: *Only the values of the `array` may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.* – salathe Aug 24 '11 at 19:33
  • @salathe: Yes, just noticed that. Working on alternative. – Evan Mulawski Aug 24 '11 at 19:35
  • This is just awful, what's wrong with a simple `array_walk()` and the loop body of @nobody's answer as the callback? – Ja͢ck Dec 18 '12 at 16:46
4
foreach( $array as &$element ) {
    $element['u_id'] = $element['id'];
    unset( $element['id'] );
}
nobody
  • 10,599
  • 4
  • 26
  • 43