PHP更改数组键 [英] PHP Change Array Keys

查看:87
本文介绍了PHP更改数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Array( 0 => 'blabla',
       1 => 'blabla',
       2 => 'blblll' ) etc..

有没有一种方法可以将所有数字键更改为名称",而无需遍历数组(因此是php函数)?

Is there a way to change all the numeric keys to "Name" without looping through the array (so a php function)?

推荐答案

如果您有要使用的键数组,请使用

If you have an array of keys that you want to use then use array_combine

给出$ keys = array('a','b','c',...)和您的数组$ list,然后执行以下操作:

Given $keys = array('a', 'b', 'c', ...) and your array, $list, then do this:

$list = array_combine($keys, array_values($list));

列表现在将是array('a'=>'blabla 1',...)等

List will now be array('a' => 'blabla 1', ...) etc.

您必须使用 array_values 来提取数组中的值,而不是旧的数字键.

You have to use array_values to extract just the values from the array and not the old, numeric, keys.

这看起来很简单,但是array_values可以复制数组的整个副本,因此您可能会遇到空间问题.我们在这里所做的就是让php为我们做循环,而不是消除循环.我很想做更多类似的事情:

That's nice and simple looking but array_values makes an entire copy of the array so you could have space issues. All we're doing here is letting php do the looping for us, not eliminate the loop. I'd be tempted to do something more like:

foreach ($list as $k => $v) {
   unset ($list[$k]);

   $new_key =  *some logic here*

   $list[$new_key] = $v;
}

我认为这没有比第一个代码更有效的方法,但是它提供了更多的控制权,并且数组长度没有问题.

I don't think it's all that more efficient than the first code but it provides more control and won't have issues with the length of the arrays.

这篇关于PHP更改数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆