如何使用多维数组将该函数转换为递归?

时间:2018-10-30 18:57:23

标签: php function recursion multidimensional-array

您好,我正在考虑如何使用具有很多层的递归函数构建此数组。 因此数据就是这样。

id belongs_to
1a  NULL
2a  NULL
3a  1a
4a  NULL
5a  2a

和非递归函数,例如:

foreach ($first_layer as $first_layer_obj) {
        $array[$first_layer_obj->id] = [];
        $second_layer = /* SELECT id FROM client WHERE belongs_to $first_layer_obj->id */;
        foreach ($second_layer as $second_layer_obj) {
            $array[$first_layer_obj->id][$second_layer_obj->id] = [];
            $third_layer = /* SELECT id FROM client WHERE belongs_to $second_layer_obj->id */;
            foreach ($third_layer as $third_layer_obj->id) {
                $array[$first_layer_obj->id][$second_layer_obj->id][$third_layer_obj->id] = [];
            }
        }

我期望输出为:

array(3) {
["1a"]=>
   array(1){
     ["3a"]=>[]
   }
["2a"]=>
   array(1){
     ["5a"]=>[]
   }
["4a"]=>[]
}

1 个答案:

答案 0 :(得分:0)

当然,第一条建议是,您应该避免对数据库执行递归/迭代调用。您应该进行一次调用,以在单个结果集中提取所有所需的行,然后让php进行困难的工作。

我决定尝试一种非递归方法。为此,必须准备结果集,以便首先列出“ grander”子级。现在,我意识到您的样本数据完全有可能不能真正代表您的项目值,并且排序不能充分用于准备结果集-您必须让我知道(也许还需要更多地更新您的问题准确的样本数据。

[请参阅内联注释,了解我的脚本中正在发生的事情]

*如果您未使用php7 +,则我的空合并运算符($row1['children'] ?? [])将引起问题。
您可以使用:(isset($row1['children']) ? $row1['children'] : []

代码:(Demo

// use ORDER BY belongs_to DESC, id ASC ... or usort() to prepare result set
$resultset = [
    ['id' => '6a', 'belongs_to' => '5a'],
    ['id' => '5a', 'belongs_to' => '3a'],
    ['id' => '8a', 'belongs_to' => '3a'],
    ['id' => '3a', 'belongs_to' => '1a'],
    ['id' => '1a', 'belongs_to' => null],
    ['id' => '2a', 'belongs_to' => null],
    ['id' => '4a', 'belongs_to' => null],
    ['id' => '7a', 'belongs_to' => null]
];

foreach ($resultset as $index1 => &$row1) {             // make input array modifiable by reference (not working with a copy)
    if ($row1['belongs_to']) {                          // original belongs_to value is not null (not a top-level parent)
        foreach ($resultset as $index2 => $row2) {      // search for targeted parent
            if ($row2['id'] == $row1['belongs_to']) {   // parent found
                $resultset[$index2]['children'][] = [$row1['id'] => $row1['children'] ?? []];  // store original row as child
                unset($resultset[$index1]);             // remove original row (no reason to iterate it again in outer loop)
                break;                                  // halt inner loop (no reason to iterate further)
            }
        }
    } else {                                            // original belongs_to value is null (top-level parent)
        $output[$row1['id']] = $row1['children'] ?? [];  // store children to top
    }
}
var_export($output);

输出:

array (
  '1a' => 
  array (
    0 => 
    array (
      '3a' => 
      array (
        0 => 
        array (
          '5a' => 
          array (
            0 => 
            array (
              '6a' => 
              array (
              ),
            ),
          ),
        ),
        1 => 
        array (
          '8a' => 
          array (
          ),
        ),
      ),
    ),
  ),
  '2a' => 
  array (
  ),
  '4a' => 
  array (
  ),
  '7a' => 
  array (
  ),
)