如何解析数组中的 true
和 false
字符串,如果它们存在则变成 boolean 值?
例如,
表格
$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"
)
);
最佳答案
您可以使用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
关于php - 如何将数组中的 true 和 false 字符串解析为 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10437960/