递归迭代器:将子属性添加到第n级的父级

时间:2015-03-09 15:21:42

标签: php arrays recursion

我正在尝试建立一个优先级系统,以便一个人可以优先考虑他直接拥有或未优先考虑的事物清单。所以TheBigCheese下面有3个Lackeys,他们又有Minions。那些奴才也可以拥有奴才,循环可以永远持续下去。我想弄清楚如何将每个Minion(和他们的Minions)的优先级添加到Lackey的优先级中,因为TheBigCheese不关心Minions的任何优先级,他只关心Lackey如何优先考虑他的事情作为他之下所有民主的事物。

["TheBigCheese"] => array(
  "myPriorities" => array(),
  "myMinions" = array(
    ["Lackey1"] => array(
      "myPriorities" => array(),
      "myMinions" => array(
        ["Minion1"] => array(
          "priorities" => array(), <--- These need to be added to Lackey1's priorities
          "myMinions" => array()
        ),
        ["Minion2"] => array(
          "priorities" => array(),  <--- These need to be added to Lackey1's priorities
          "myMinions" => array(
             ["Minion3"] => array(
               "priorities" => array(), <--- These need to be added to Lackey1's priorities
               "myMinions" => array()
             )
          ) // End Minion2's Minions
        )
      ) // End Lackey1's Minions
    ),
    ["Lackey2"]  => array(
      "myPriorities" => array(),
      "myMinions" => array()
    ),
    ["Lackey3"] => array(
      "myPriorities" => array(),
      "myMinions" => array()
    )
  ) //End BigWig's minions
);

1 个答案:

答案 0 :(得分:0)

您需要一个函数来运行递归,然后预先处理每个顶级(199和50)。像这样:

$myArray = [199 => array(...), 50 => array(...)];
foreach($myArray as &$subArray) {
    $subArray['allChildren'] = recursiveSearch($subArray);
}

function recursiveSearch($array) {
    $allChildren = array();
    foreach($array as $key => $child) {
        $allChildren[] = $key;
        if(is_array($child)) {
            $tempArray = recursiveSearch($child);
            $allChildren = array_merge($allChildren, $temp);
        }
    }
    return $allChildren;
}

我没有对这项工作进行过测试,但它应该可以帮助你。