php 如何用数组中的值交换键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6845037/
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
How to swap keys with values in array?
提问by daGrevis
I have array like:
我有这样的数组:
array(
0 => 'a',
1 => 'b',
2 => 'c'
);
I need to convert it to:
我需要将其转换为:
array(
'a',
'b',
'c'
);
What's the fastest way to swap keys with values?
用值交换键的最快方法是什么?
回答by Haim Evgi
PHP has the array_flip
function which exchanges all keys with their corresponding values, but you do not need it in your case because the arrays are the same.
PHP 具有将array_flip
所有键与其对应的值交换的功能,但在您的情况下不需要它,因为数组是相同的。
array(
'a',
'b',
'c'
);
This array has the keys 0, 1, and 2.
该数组具有键 0、1 和 2。
回答by Shef
Use array_flip()
. That will do to swap keys with values. However, your array is OK the way it is. That is, you don't need to swap them, because then your array will become:
使用array_flip()
. 这将用于交换键与值。但是,您的阵列按原样是可以的。也就是说,您不需要交换它们,因为这样您的数组将变为:
array(
'a' => 0,
'b' => 1,
'c' => 2
);
not
不是
array(
'a',
'b',
'c'
);
回答by Fabio
array(
0 => 'a',
1 => 'b',
2 => 'c'
);
and
和
array(
'a',
'b',
'c'
);
are the same array, the second form has 0,1,2 as implicit keys. If your array does not have numeric keys you can use array_valuesfunction to get an array which has only the values (with numeric implicit keys).
是同一个数组,第二种形式有 0,1,2 作为隐式键。如果你的数组没有数字键,你可以使用array_values函数来获取一个只有值的数组(带有数字隐式键)。
Otherwise if you need to swap keys with values array_flipis the solution, but from your example is not clear what you're trying to do.
否则,如果您需要将键与值交换,则array_flip是解决方案,但从您的示例中并不清楚您要做什么。
回答by Yoshi
See: array_flip
请参阅:array_flip
回答by PtPazuzu
$flipped_arr = array_flip($arr);
will do that for you.
$flipped_arr = array_flip($arr);
会为你做的。
回答by Lukas Knuth
You'll want to use array_flip()
for that.
你会想要使用array_flip()
它。