php 如何将简单数组转换为关联数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6153360/
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 convert a simple array to an associative array?
提问by user773755
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])
?
在 PHP 中将简单数组转换为关联数组以便可以在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;
}
采纳答案by Felix Kling
array_flip()
is exactly doing that:
array_flip()
正是这样做:
array_flip()returns an arrayin flip order, i.e. keys from transbecome values and values from transbecome keys.
Note that the values of transneed to be valid keys, i.e. they need to be either integeror 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.
array_flip()按翻转顺序返回一个数组,即来自trans 的键变为值,来自trans 的值变为键。
请注意,trans的值必须是有效的键,即它们必须是integer或string。如果值的类型错误,则会发出警告,并且不会翻转有问题的键/值对。
如果某个值出现多次,则将使用最新的键作为其值,而所有其他键都将丢失。
But apart from that, there is only one type of array in PHP. Even numerical ("simple", as you call it) arrays are associative.
但除此之外,PHP 中只有一种类型的数组。甚至数字(“简单”,如您所称)数组也是关联的。
回答by Alix Axel
Your code is the exact equivalent of:
您的代码完全等同于:
$assoc = array_fill_keys(array(1, 2, 3, 4, 5), 1); // or
$assoc = array_fill_keys(range(1, 5), 1);
array_flip()
, while it may work for your purpose, it's not the same.
array_flip()
,虽然它可能适用于您的目的,但它并不相同。
PHP ref: array_fill_keys()
, array_flip()
PHP 参考:array_fill_keys()
,array_flip()
回答by A.M.N.Bandara
If anyone is still wondering how to do this, there is an easier solution for this by using the array_combinefunction.
如果有人仍然想知道如何做到这一点,使用array_combine函数有一个更简单的解决方案。
$array = array(1, 2, 3, 4, 5);
$assoc = array_combine($array,$array);
回答by Thyagi
Simply use this logic
简单地使用这个逻辑
$var1 = json_encode($arr1, JSON_FORCE_OBJECT);
$var1 = json_decode($var1);
where $arr1 is the array that has to be converted to associative array. This can be achieved by json_encode and the json_decode the same
其中 $arr1 是必须转换为关联数组的数组。这可以通过 json_encode 和 json_decode 相同来实现
回答by Adrian
function simple_to_associative($array) {
$new_array = [];
$i = 0;
$last_elem = end($array);
$nr_elems = count($array);
foreach ($array as $index=>$value) {
if($i % 2 == 0 && $last_elem == $value) {
$new_array[$value] = '';
} elseif($i % 2 == 0) {
$new_array[$value] = $array[$index + 1];
}
$i++;
}
return $new_array;
}
Would work on any simple array of unlimited elements.
可以处理任何简单的无限元素数组。