PHP阵列 - 打开阵列值放入钥匙 [英] PHP Array - Turning Array values into Keys

查看:146
本文介绍了PHP阵列 - 打开阵列值放入钥匙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是有值的数组,并把它变成键数组的最有效方法是什么?
我真的想避免任何foreach循环......

  $ =在阵列(
    '红',
    '绿色',
    '蓝色'
);

INTO

  $ OUT =阵列(
    '红'=>空值,
    绿色= GT;空值,
    '蓝'=>空值
);


解决方案

使用PHP的 array_flip 功能。



退一步讲,如果你想要的值是零,那么你可能想使用<一个href=\"http://www.php.net/manual/en/function.array-fill-keys.php\"><$c$c>array_fill_keys:

  $ OUT = array_fill_keys($的,NULL);

What is the MOST EFFICIENT way to have an array of values and turn it into an array of keys? I'd really like to avoid any foreach loop...

$in = array(
    'red',
    'green',
    'blue'
);

INTO

$out = array(
    'red' => NULL,
    'green' => NULL,
    'blue' => NULL
);

解决方案

Use PHP's array_flip function.


On second thought, if you want the values to be null, then you might want to use array_fill_keys:

$out = array_fill_keys($in, null);

这篇关于PHP阵列 - 打开阵列值放入钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆