"true", -6ren">
gpt4 book ai didi

php - 如何将数组中的 true 和 false 字符串解析为 boolean 值

转载 作者:可可西里 更新时间:2023-11-01 13:37:13 25 4
gpt4 key购买 nike

如何解析数组中的 truefalse 字符串,如果它们存在则变成 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com