- Use
array_combine
to create the result.
array_combine ( array $keys , array $values ) : array
Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.
Pass your original array as both the keys and values to create the desired outcome
<?php
$array = [];
$array[0] = 'foo';
$array[1] = 'bar';
$res = array_combine($array, $array);
print_r($res);
Array
(
[foo] => foo
[bar] => bar
)
Try it online!
The above solution does not work when applying multidimensional arrays.
You'll need to 'flatten' the array before passing to array_combine
to get the desired values;
<?php
$array = [];
$array[] = 'foo';
$array[1] = 'bar';
$array[2] = [ 'foobar', 'barfoo' ];
$values = flat($array);
$res = array_combine($values, $values);
print_r($res);
function flat($array) {
$values = [];
array_walk_recursive($array, function($a) use (&$values) { $values[] = $a; });
return $values;
}
Array
(
[foo] => foo
[bar] => bar
[foobar] => foobar
[barfoo] => barfoo
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…