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

1
  • What have you tried so far so it saves our time trying what you have already tried? Commented Aug 24, 2011 at 19:37

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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: Yes, just noticed that. Working on alternative.
This is just awful, what's wrong with a simple array_walk() and the loop body of @nobody's answer as the callback?
4
foreach( $array as &$element ) {
    $element['u_id'] = $element['id'];
    unset( $element['id'] );
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.