数组将值复制到 PHP 中的键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6175548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:34:47  来源:igfitidea点击:

Array copy values to keys in PHP

phparrays

提问by kusanagi

I have this array:

我有这个数组:

$a = array('b', 'c', 'd');

Is there a simple method to convert the array to the following?

有没有一种简单的方法可以将数组转换为以下内容?

$a = array('b' => 'b', 'c' => 'c', 'd' => 'd');

回答by KingCrunch

$final_array = array_combine($a, $a);

$final_array = array_combine($a, $a);

http://php.net/array-combine

http://php.net/array-combine

P.S.

* Be careful with similar values. For example:
array('one','two','one')may be problematic if converted like duplicate keys:
array('one'=>..,'two'=>..,'one'=>...)

PS

* 小心类似的值。例如:
array('one','two','one')如果像重复键一样转换可能会有问题:
array('one'=>..,'two'=>..,'one'=>...)

回答by sebke CCU

Be careful, the solution proposed with $a = array_combine($a, $a);will not work for numeric values.

请注意,提出的解决方案$a = array_combine($a, $a);不适用于数值。

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384)to be the keys as well as the values however PHP manual states:

例如,我希望有一个内存array(128,256,512,1024,2048,4096,8192,16384)作为键和值,但是 PHP 手册指出:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

如果输入数组具有相同的字符串键,则该键的后一个值将覆盖前一个。但是,如果数组包含数字键,则后面的值不会覆盖原始值,而是会附加。

So I solved it like this:

所以我是这样解决的:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}