如何将简单的数组转换为一个关联数组? [英] How to convert a simple array to an associative array?
问题描述
什么是一个简单的数组转换为PHP关联数组,这样的值可以在使用isset检查以最快的方式($数组[$值])
?
即。做下面的转换最快的方式:
$阵列=阵列(1,2,3,4,5);
$ ASSOC =阵列();的foreach($数组作为$ I => $值){
$ ASSOC [$值] = 1;
}
<一个href=\"http://php.net/manual/en/function.array-flip.php\"><$c$c>array_flip()$c$c>也正是这样做的:
array_flip()返回翻转阵列顺序,即从按键的跨的成为从的跨的成为键的值和值。
请注意,值的跨的必须是有效的密钥,即他们需要作的整数或字符串。如果值类型错误的警告将会发出,并有问题的键/值对的不会被翻转的
如果一个值具有若干事件,最新的密钥将被用来作为它的值,而所有其他人将被丢失。
块引用>但除此之外,只有一种类型在PHP阵列。即使是数字(简单,你称呼它)数组是关联的。
What is the fastest way to convert a simple array to an associative array in PHP so that values can be checked in the
isset($array[$value])
?I.e. fastest way to do the following conversion:
$array = array(1, 2, 3, 4, 5); $assoc = array(); foreach ($array as $i => $value) { $assoc[$value] = 1; }
解决方案
array_flip()
is exactly doing that:array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.
Note that the values of trans need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be flipped.
If a value has several occurrences, the latest key will be used as its values, and all others will be lost.
But apart from that, there is only one type of array in PHP. Even numerical ("simple", as you call it) arrays are associative.
这篇关于如何将简单的数组转换为一个关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!