背景和目标
如果您需要更多背景信息,则可以查看该问题的过往修改。为了使它成为minimal reproducible example,我已将其缩减了很多。
我需要一个函数check()
来检查多维数组,以查看其是否具有“必需”键以及这些键的值是否不为空。
所以...有:
$subject
:将要检查的数组$required
:将用于检查$subject
check()
:同时接受上述参数和“比较”的函数问题与意见
$subject
数组的结构是多维的,并且不统一。一个第一级键可以具有单个值...或者它可以是一个数组的数组,一个数组的数组,等等...请记住,check()
函数似乎需要递归性质。 / p>
主要问题
我正在努力如何递归地进行这项工作,或者在可能的情况下,这是避免无限级别的if
条件/ foreach
循环的最佳选择。
“ /主要问题* /”下方的代码中详细说明了“主要问题”。
功能
function check($subject, $required) {
foreach ($required as $main_key => $main_val) {
// need to iterate through more dimensions
if (is_array($main_val)) {
foreach ($main_val as $sub_key => $sub_val) {
/* MAIN PROBLEM HERE */
// $sub_val COULD be another array if there was another dimension to $subject ...
// I need an alternative to avoid infinite if conditions / foreach loops
if (!isset($subject[$main_key][$sub_val])) {
echo "ERROR: Required value is null: {$main_key}[{$sub_val}]";
return false;
}
}
// no more dimensions to iterate through
} else {
if (!isset($subject[$main_val])) {
echo "ERROR: Required value is null: {$main_val}";
return false;
}
}
}
// all required values are set
return true;
}
输入和输出示例
/**
* Example - no errors
*/
// our subject
$product_info = array(
// 3 dimensions
'other' => array('discount' => array('amount' => 10, 'enabled' => true)),
// 2 dimensions
'prices' => array('cash' => '100', 'credit' => '103'),
// 1 dimension
'quantity' = 10
);
// our requirements
$required = array(
// 3 dimensions
'other' => array('discount' => array('amount', 'enabled')),
// 2 dimensions
'prices' => array('cash', 'credit'),
// 1 dimension
'quantity'
);
// check the array
$x = check($product_info, $required);
// Output:
/**
* Example - missing input // see that prices[credit] is commented out
*/
// our subject
$product_info = array(
// 3 dimensions
'other' => array('discount' => array('amount' => 10, 'enabled' => true)),
// 2 dimensions
// prices[credit] is commented out
'prices' => array('cash' => '100', /*'credit' => '103'*/),
// 1 dimension
'quantity' = 10
);
// our requirements
$required = array(
// 3 dimensions
'other' => array('discount' => array('amount', 'enabled')),
// 2 dimensions
// see here that we require prices[credit]
'prices' => array('cash', 'credit'),
// 1 dimension
'quantity'
);
// check the array
$x = check($product_info, $required);
// Output: ERROR: Required value is null: prices[credit]