Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

php - Create associative array containing values of original array as both keys and values

Is there a function for creating an associative array with the values of the original array as both key and value? I already looked at array_flip and array_keys but they don't seem to be able to create this.

Say i have this array:

[0 => 'foo', 1 => 'bar']

And i want to convert this to:

[foo => 'foo', bar => 'bar']

Obviously this would work, but i'm looking for a function.

$array = [];
foreach ($original_Arr as $key => $value) {$choices[$value] = $value;}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. 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
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...