跟进这个问题和答案,我决定只接受布尔值 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.';