开发者

How to re-assign array keys to turn into an associative array?

I have an array that looks something like开发者_运维技巧 this:

array(
    0 => 'John',
    1 => 'Smith',
    3 => '123-456-7890'
    4 => 'john.smith@company.com'
)

And I would like to programmatically change the keys so that the array becomes an associative array:

array(
    'first' => 'John',
    'last'  => 'Smith',
    'phone' => '123-456-7890'
    'email' => 'john.smith@company.com'
)

What is the cleanest/most concise way of doing this?


The array_combine() function is probably what you were looking for:

$keys = array('first', 'last', 'phone', 'email');

$new_arr = array_combine($keys, $arr);


array_combine is probably the optimal approach here. If you have an ordered list you can merge it with the original keys again using:

$array = array_combine(array("first", "last", "phone", "email"), $list);


Assuming the array keys are constant, such that 0 is always firstname, 1 is last name, etc...

$new_keys = array(0 => 'first', 1 => 'last', 3 => 'phone', 4 => 'email');

foreach($new_keys as $oldkey => $newkey) {
   $orig_array[$newkey] = $orig_array[$oldkey];
   unset($orig_aray[$oldkey]);
}

If the mapping isn't constant, thne you'd have to build the $new_keys array dynamically each time, or just do the remapping by hand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜