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

标签 php arrays boolean

如何解析数组中的 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/

相关文章:

ruby - 在 Ruby 中创建或附加到数组

boolean - 如何在 COBOL 中返回 true

c - 为什么在 stdbool.h 中使用整数而不是无符号整数?

php - 创建和更新 Zend_Search_Lucene 索引

arrays - Ocaml中带有参数的类型的数组

php - 无法执行mysql语句

c# - 将较小的 n 维数组放入较大数组的最快方法(二维图形类比 : paint rectangle on canvas)

java - 如何将 boolean 返回值调用到其他方法中?

PHP:在 $_SESSION 中存储 'objects'

php - 如果多个 where 条件为空值,Mysql 将返回空行