この質問と回答のフォローアップとして、ブール値の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.';