php 从常规数组创建具有相等键和值的关联数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1066850/
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 00:51:20  来源:igfitidea点击:

Create an assoc array with equal keys and values from a regular array

phparrays

提问by jimiyash

I have an array that looks like

我有一个看起来像的数组

$numbers = array('first', 'second', 'third');

I want to have a function that will take this array as input and return an array that would look like:

我想要一个函数,将这个数组作为输入并返回一个如下所示的数组:

array(
'first' => 'first',
'second' => 'second',
'third' => 'third'
)

I wonder if it is possible to use array_walk_recursiveor something similar...

我想知道是否可以使用array_walk_recursive或类似的东西......

回答by Noah Medling

You can use the array_combinefunction, like so:

您可以使用该array_combine功能,如下所示:

$numbers = array('first', 'second', 'third');
$result = array_combine($numbers, $numbers);

回答by Artem Russakovskii

This simple approach should work:

这种简单的方法应该有效:

$new_array = array();
foreach($numbers as $n){
  $new_array[$n] = $n;
}

You can also do something like:

您还可以执行以下操作:

array_combine(array_values($numbers), array_values($numbers))

array_combine(array_values($numbers), array_values($numbers))

回答by Alan Storm

This should do it.

这应该这样做。

function toAssoc($array) {
    $new_array = array();
    foreach($array as $value) {
        $new_array[$value] = $value;
    }       
    return $new_array;
}