PHP 分解填充键而不是值
PHP Explode Populate Keys Not Values
假设您有一个逗号分隔的字符串:
$str = 'a,b,c';
调用 explode(',', $str);
将 return 以下内容:
array('a', 'b', 'c')
有没有办法分解生成的数组的键而不是值?像这样:
array('a' => null, 'b' => null, 'c' => null)
像这样:
$str = 'a,b,c';
$arr = [];
foreach ($explode(',', $str) as $key) {
$arr[$key] = null;
}
不是很漂亮,但很管用
您可以使用 array_fill_keys
将 explode
的输出用作具有给定值的新数组的键:
$str = 'a,b,c';
$out = array_fill_keys(explode(',', $str), null);
var_dump($out);
输出:
array(3) {
["a"]=>
NULL
["b"]=>
NULL
["c"]=>
NULL
}
你可以简单地使用 explode with foreach
$res = [];
foreach(explode(",", $str) as $key){
$res[$key] = null;
}
print_r($res);
假设您有一个逗号分隔的字符串:
$str = 'a,b,c';
调用 explode(',', $str);
将 return 以下内容:
array('a', 'b', 'c')
有没有办法分解生成的数组的键而不是值?像这样:
array('a' => null, 'b' => null, 'c' => null)
像这样:
$str = 'a,b,c';
$arr = [];
foreach ($explode(',', $str) as $key) {
$arr[$key] = null;
}
不是很漂亮,但很管用
您可以使用 array_fill_keys
将 explode
的输出用作具有给定值的新数组的键:
$str = 'a,b,c';
$out = array_fill_keys(explode(',', $str), null);
var_dump($out);
输出:
array(3) {
["a"]=>
NULL
["b"]=>
NULL
["c"]=>
NULL
}
你可以简单地使用 explode with foreach
$res = [];
foreach(explode(",", $str) as $key){
$res[$key] = null;
}
print_r($res);