在此question and answer之後,我決定接受來自其他開發人員/用戶的輸入的布爾真和假,並且而不是甚至null
。PHP is_null:只有布爾值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.';
謝謝Jordy,'array_key_exists'修復了我的問題! :-) – laukok