我有一个多维关联数组,其中每个节点可以有可变数量的子节点。每个子节点将在某个点以布尔节点结束。我想做的是这样做,如果所有子节点以false结束,父节点将从数组更改为布尔值false。
输入数组示例:
[
[Agronomy] => [
[blendingAnhydrous] => [
[blendingSprayOrdersDeliveryTkts] => [
[add] => true,
[create] => true,
[inquire] => true,
[delete] => true
],
[historyInquiry] => [
[add] => false,
[create] => true,
[inquire] => false,
[delete] => true
],
[listAnhydrousTicketsToBeBilled] => [
[add] => false,
[create] => false,
[inquire] => false,
[delete] => false
],
],
[main] => [
[agronomyBlendingAnhydrousEntry]: false,
[agronomyRecomendationsHistory]: false,
[agronomyReports]: false,
[agronomySetup]: false
],
],
[Grain] => [
[main] => [
[option1] => false,
[option2] => false,
[option3] => false,
]
]
]
期望输出数组:
[
[Agronomy] => [
[blendingAnhydrous] => [
[blendingSprayOrdersDeliveryTkts] => [
[add] => true,
[create] => true,
[inquire] => true,
[delete] => true
],
[historyInquiry] => [
[add] => false,
[create] => true,
[inquire] => false,
[delete] => true
],
[listAnhydrousTicketsToBeBilled] => false
],
[main] => false
],
[Grain] => false
]
我试过的代码:
function collapseAuthorities(&$complexArray)
{
$keepExpanded = false;
foreach ($complexArray as $node => $value) {
if (is_array($value)) {
$this->collapseAuthorities($value);
if (!$keepExpanded) {
$value = false;
}
} elseif ($value === true) {
$keepExpanded = true;
}
}
}
我已经浏览了很多关于多维数组的SO问题,但还没有找到任何可以完全回答这个场景的问题。
您需要递归地扫描$值:
$rewriteArray = array();
foreach($mainParentArray as $key=>$value) {
$rewriteArray[$key] = decompose($value);
}
function decompose($value) {
if (is_array($value)) {
list($array_as_value, $false_found) = keyScan($value);
if ($array_as_value) {
dendriticReconstruct($value);
} else {
$return = $false_found ? false : $value;
}
} else {
$return = $value;
}
return $return;
}
function keyScan($value) {
$array_as_value = $false_found = false;
foreach($value as $k=>$v) {
if (is_array($v)) {
$array_as_value = true;
break;
} else {
if ($v === false) {
$false_found = true;
break;
}
}
}
return array($array_as_value, $false_found);
}
function dendriticReconstruct($value) {
//use method found at this post ---> http://stackoverflow.com/questions/2504685/php-find-parent-key-of-array
}
我不能完全完成它——它花了我太长时间。我希望这能让你朝着正确的方向开始!