talkpoppycock
talkpoppycock

Reputation: 147

Changing the keys of as two dimensional array

I have a two dimensional array and I need to change the keys of the inner arrays as follows:

From:

Array
(
    [1] => Array
        (
            [A] => 1
            [B] => John
            [C] => Doe
            [D] => Mr
        )

    [2] => Array
        (
            [A] => 2
            [B] => Jane
            [C] => Doe
            [D] => Mrs
        )

    [3] => Array
        (
            [A] => 5
            [B] => Jill
            [C] => Smith
            [D] => Miss
        )
)

To:

Array
(
    [1] => Array
        (
            [id] => 1
            [first_name] => John
            [last_name] => Doe
            [title] => Mr
        )

    [2] => Array
        (
            [id] => 2
            [first_name] => Jane
            [last_name] => Doe
            [title] => Mrs
        )

    [3] => Array
        (
            [id] => 5
            [first_name] => Jill
            [last_name] => Smith
            [title] => Miss
        )
)

Changing the values is straight forward, but I have no idea how to change the keys and can't find any useful suggestions. Can anyone help please?

Upvotes: 0

Views: 151

Answers (2)

The fourth bird
The fourth bird

Reputation: 163217

If there are always 4 items and the order does not change, you could create a $keys array and using array_combine inside array_map:

$keys = [
    "id",
    "first_name",
    "last_name",
    "title"
];
$array = [
    1 => ["A" => 1, "B" => "John", "C" => "Doe", "D" => "Mr"],
    2 => ["A" => 2, "B" => "Jane", "C" => "Doe", "D" => "Mrs"],
    3 => ["A" => 5, "B" => "Jill", "C" => "Smith", "D" => "Miss"],
];
$result = array_map(function ($x) use ($keys) {
    return array_combine($keys, $x);
}, $array);
print_r($result);

Output

Array
(
    [1] => Array
        (
            [id] => 1
            [first_name] => John
            [last_name] => Doe
            [title] => Mr
        )

    [2] => Array
        (
            [id] => 2
            [first_name] => Jane
            [last_name] => Doe
            [title] => Mrs
        )

    [3] => Array
        (
            [id] => 5
            [first_name] => Jill
            [last_name] => Smith
            [title] => Miss
        )

)

Php demo

Upvotes: 2

Shahin
Shahin

Reputation: 91

It will reformat and update old array:

$map = [
    'A' => 'id',
    'B' => 'first_name',
    'C' => 'last_name',
    'D' => 'title',
    
];

foreach($your_array as $key => &$innerArray) {
    $newInnerArray = [];
    
    foreach($innerArray as $ik => $iv) {
        $newInnerArray[$map[$ik]] = $iv;
    }
    
    
    $innerArray = $newInnerArray;   
}

Upvotes: 1

Related Questions