How to replace array key by its value

时间:2022-03-11 22:08:26

I have the following array:

我有以下数组:

array('Elnett', 'INOA INOA', 'Playball P', 'Preferred Color Specialist', 
      'Série Expert', 'Série Nature', 'Techni art')

I would like to have keys and values like:

我想要键和值如:

array('Elnett' => 'Elnett', 
      'INOA INOA' => 'INOA INOA', 
      'Playball P' => 'Playball', 
      'Preferred Color Specialis' => 'Preferred Color Specialist', 
      'Série Expert' => 'Série Expert', 
      'Série Nature' => 'Série Nature', 
      'Techni art' => 'Techni art')

How can I accomplish this?

我怎么能做到这一点?

4 个解决方案

#1


2  

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

print_r($out);

#2


23  

There's array_combine to create a key/value array out of two arrays. Should be possible to use the same array for keys and values:

有array_combine从两个数组中创建一个键/值数组。应该可以为键和值使用相同的数组:

$names = array_combine($names, $names);

#3


5  

This one-line answer may be useful to someone.

这个单行答案可能对某人有用。

$trans = array_flip($array);

http://us1.php.net/array_flip

array_flip returns the value=>key format of given key=>value array. as the question changed, this does not exactly answer the OP's question anymore.

array_flip返回给定key => value数组的value => key格式。随着问题的改变,这并不能完全回答OP的问题。

#4


1  

Could do something like this. Not sure if there is a cleaner way to do it.

可以做这样的事情。不确定是否有更清洁的方法来做到这一点。

foreach($names as $key => $name){
    $names[$name] = $name;
    unset($names[$key]);
}

#1


2  

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

print_r($out);

#2


23  

There's array_combine to create a key/value array out of two arrays. Should be possible to use the same array for keys and values:

有array_combine从两个数组中创建一个键/值数组。应该可以为键和值使用相同的数组:

$names = array_combine($names, $names);

#3


5  

This one-line answer may be useful to someone.

这个单行答案可能对某人有用。

$trans = array_flip($array);

http://us1.php.net/array_flip

array_flip returns the value=>key format of given key=>value array. as the question changed, this does not exactly answer the OP's question anymore.

array_flip返回给定key => value数组的value => key格式。随着问题的改变,这并不能完全回答OP的问题。

#4


1  

Could do something like this. Not sure if there is a cleaner way to do it.

可以做这样的事情。不确定是否有更清洁的方法来做到这一点。

foreach($names as $key => $name){
    $names[$name] = $name;
    unset($names[$key]);
}