如何解析数组中的true
和false
字符串,如果存在则成为布尔值?
例如,
表格
$config = array(
"allow_n" => "true",
"allow_m" => "false",
"say" => "hello"
);
到
$config = array(
"allow_n" => true,
"allow_m" => false,
"say" => "hello"
);
有可能吗?
修改
谢谢大家的帮助。
抱歉,我忘了从头开始澄清 - 这种情况可能发生在多元数组中,例如,
$config = array(
"allow_n" => "true",
"allow_m" => "false",
"say" => "Hello",
"php" => array(
"oop" => "true",
"classic" => "false"
)
);
答案 0 :(得分:5)
您可以使用array_walk_recursive
来实现此目标:
示例
$config = array (
"allow_n" => "true",
"allow_m" => "false",
"say" => "Hello",
"php" => array (
"oop" => "true",
"classic" => "false"
)
);
var_dump ( $config );
array_walk_recursive ( $config, function (&$item) {
if ($item == "true") {
$item = true;
} else if ($item == "false") {
$item = false;
} else if (is_numeric ( $item )) {
$item = intval ( $item );
}
} );
var_dump ( $config );
之前输出
'allow_n' => string 'true' (length=4)
'allow_m' => string 'false' (length=5)
'say' => string 'Hello' (length=5)
'php' =>
array
'oop' => string 'true' (length=4)
'classic' => string 'false' (length=5)
之后的输出
array
'allow_n' => boolean true
'allow_m' => boolean false
'say' => string 'Hello' (length=5)
'php' =>
array
'oop' => boolean true
'classic' => boolean false
答案 1 :(得分:4)
foreach ($config as $k=>$v)
{
$low_v = strtolower($v);
if ($low_v == 'true')
$config[$k] = true;
else if ($low_v == 'false')
$config[$k] = false;
}
答案 2 :(得分:2)
这是一个可以做到这一点的循环
foreach ($config as $key => $val) {
if ($val == 'true') {
$config[$key] = true;
} elseif ($val == 'false') {
$config[$key] = false;
}
}
编辑:这是一个递归和处理多维数组的函数
function tfSwap($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = tfSwap($val);
} else {
if ($val == 'true') {
$arr[$key] = true;
} elseif ($val == 'false') {
$arr[$key] = false;
}
}
}
return $arr;
}
然后你就可以这样称呼它:
$config = tfSwap($config);
答案 3 :(得分:2)
我确定还有其他解决方案,但您应该能够使用filter_var
函数并传入FILTER_VALIDATE_BOOLEAN
标记。那会给你一个单行代替而不是写出一个循环。 :)
filter_var($config, FILTER_VALIDATE_BOOLEAN);
//编辑:与此处建议相同:How to parse a string of boolean logic in PHP
答案 4 :(得分:2)
你也可以维护一个转换数组,并在迭代数组的同时查看它。
$map = array("true" => true, "false" => false);
foreach ($config as $key => $value) {
if (array_key_exists($value, $map)) {
$config[$key] = $map[$value];
}
}
答案 5 :(得分:1)
我的方法就像:
function boolify( $var ) {
if( is_array( $var ) ) foreach( $var as $ek=>$ev ) $ret[$ek] = boolify( $ev );
else if( $var === 'false' ) $ret = false;
else if( $var === 'true' ) $ret = true;
else $ret = $var;
return $ret;
}
$config = array(
"allow_n" => "true",
"allow_m" => "false",
"say" => "Hello",
"php" => array(
"oop" => "true",
"classic" => "false"
)
);
$config = boolify( $config );
var_dump( $config );
// output: array(4) { ["allow_n"]=> bool(true) ["allow_m"]=> bool(false) ["say"]=> string(5) "Hello" ["php"]=> array(2) { ["oop"]=> bool(true) ["classic"]=> bool(false) } }