Search code examples
phparraysmultidimensional-arrayreplacekey

Remap keys in each row of a 2d array to replace string keys with new string keys


I have an array like the one below

Array
(
    [0] => Array
        (
            [name] => Alex
            [age] => 30
            [place] => Texas                
        )

    [1] => Array
        (
            [name] => Larry
            [age] => 28
            [place] => Memphis

        )

)

How would I change the key names? Like "name" to "firstname", "age" to "years", "place" to "address"?


Solution

  • array_map is your friend,

    $users = array_map(function($user) {
        return array(
            'firstname' => $user['name'],
            'years' => $user['age'],
            'location' => $user['place']
        );
    }, $users);
    

    DEMO.