How to convert a simple array to an associative ar

2019-03-17 10:57发布

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;
}

4条回答
该账号已被封号
2楼-- · 2019-03-17 11:13

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

查看更多
叛逆
3楼-- · 2019-03-17 11:22

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.

查看更多
Luminary・发光体
4楼-- · 2019-03-17 11:28

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.

PHP ref: array_fill_keys(), array_flip()

查看更多
叼着烟拽天下
5楼-- · 2019-03-17 11:32

If anyone is still wondering how to do this, there is an easier solution for this by using the array_combine function.

$array = array(1, 2, 3, 4, 5);
$assoc = array_combine($array,$array);
查看更多
登录 后发表回答