2

跟进这个问题和答案,我决定只接受布尔值 true 和 false,甚至null接受其他开发人员/用户的输入。

$default = array(
    "category_id"   =>  null,
    "category"      =>  false,
    "randomise"     =>  false
);

$config = array(
    "category_id"   =>  17,
    "randomise"     =>  false, 
    "category"      =>  null
);

function process_array($default,$config)
{
    # Set empty arrays for error & items.
    $error = array();
    $items = array();

    # Loop the array.
    foreach($default as $key => $value)
    {
        if (is_bool($default[$key]) && isset($config[$key])) 
        {
            if ($config[$key] === null) $error[] = '"'. $key.'" cannot be null.';

            # Make sure that the value of the key is a boolean.
            if (!is_bool($config[$key])) 
            {
                $error[] = '"'. $key.'" can be boolean only.';
            }

        }

            if(isset($config[$key]) && !is_array($value))
            {
                $items[$key] = $config[$key];
            }
            elseif(isset($config[$key]) && is_array($value))
            {
                $items[$key] = array_merge($default[$key], $config[$key]);
            }
            else
            {
                $items[$key] = $value;
            }
        }

        # Give a key to the error array.
        $error = array("error" => $error);

        # Merge the processed array with error array.
        # Return the result.
        return array_merge($items,$error);
}

print_r(process_array($default,$config));

但我得到的结果是,

Array
(
    [category_id] => 17
    [category] => 
    [randomise] => 
    [error] => Array
        (
        )

)

我追求的结果,

Array
(
    [category_id] => 17
    [category] => 
    [randomise] => 
    [error] => Array
        (
         [0] => "category" cannot be null.
        )

)

所以我认为下面的这条线应该可以工作,但我不明白为什么它不起作用。我尝试使用is_null但仍然无法正常工作。知道我做错了什么,我该如何解决这个问题?

if ($config[$key] === null) $error[] = '"'. $key.'" cannot be null.';
4

3 回答 3

3

我相信一个null值不会通过isset()测试if (is_bool($default[$key]) && isset($config[$key])),所以它会跳过整个块。

我认为你需要进行一些重构来解决这个问题。也许从 if 中取出 isset 并将其移至 null 测试?

if (!isset($config[$key]) || is_null($config[$key])) $error[] = '"'. $key.'" cannot be null.';

于 2012-09-18T12:41:02.797 回答
2

isset($config[$key])如果值为 null,则返回 false。改用array_key_existshttp://php.net/manual/function.array-key-exists.php)。

于 2012-09-18T12:44:19.453 回答
1

null也不会通过is_bool检查......据我所知 - 说到if statements- 最好尽可能简单:

if (is_null($default[$key]))
{
  $error[] = '"'. $key.'" cannot be null.';
}
else if (!is_bool($default[$key])) 
{
  $error[] = '"'. $key.'" can be boolean only.';
}

正如另一张海报所说,最好将上述内容包装起来array_key_exists以避免非法偏移警告。Tbh,为了简单起见,您真的需要这两项检查吗?指定key只能是布尔值就足够了。

于 2012-09-18T12:44:43.937 回答