1

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"?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
user2509780
  • 121
  • 2
  • 9

3 Answers3

2

Use a foreach loop to iterate over your array, and then use array_combine in conjunction with array_values() to create the new array:

$keys = array('firstname', 'years', 'address');
foreach ($array as & $subarr) {
    $subarr = array_combine($keys, array_values($subarr));
}

print_r($array);

Output:

Array
(
    [0] => Array
        (
            [firstname] => Alex
            [years] => 30
            [address] => Texas
        )

    [1] => Array
        (
            [firstname] => Larry
            [years] => 28
            [address] => Memphis
        )

)

Online demo

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • I'm baffled by the downvote; it would be nice for the downvoter to explain why he/she thinks this is an unhelpful and/or incorrect response so I can, perhaps, improve it. – Amal Murali Feb 28 '14 at 13:12
1

array_map is your friend,

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

DEMO.

Rikesh
  • 26,156
  • 14
  • 79
  • 87
  • 2
    @GuyT: This is a valid solution (a more functional approach than mine). But [my answer](http://stackoverflow.com/a/22096142/1438393) was downvoted too :/ – Amal Murali Feb 28 '14 at 13:13
  • I baffled too. At-least he should comment the reason for down vote. – Rikesh Feb 28 '14 at 13:16
0

I believe that the only way to do this is to create a new array and assign each value with old key to value with new key.

<?php
    //$originalArray is array from the question.
    for($i=0; $i<=count($originalArray); $i++){
        $originalArray[$i] = rekeyArray($originalArray[$i]);
    }

    function rekeyArray($a){
        $result = array();

        if(isset($a['name']))
        $result['firstname'] = $a['name'];

        if(isset($a['age']))
        $result['years'] = $a['age'];

        if(isset($a['place']))
        $result['address'] = $a['place'];

        return $result;
    }
?>
jan
  • 2,879
  • 2
  • 19
  • 28