Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change array key of this array? [duplicate]

Tags:

arrays

php

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

like image 419
Gihan Lasita Avatar asked Dec 27 '22 15:12

Gihan Lasita


1 Answers

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.

like image 196
Evan Mulawski Avatar answered Jan 05 '23 14:01

Evan Mulawski