从数据库中的菜单构建嵌套数组


Build a nested array from a menu in database

我有以下来自数据库的输出,我想用这些数据构建一个菜单。

$output = [
    ['id_struct' => 1, 'title' => 'A', 'parent' => 0],
    ['id_struct' => 2, 'title' => 'B', 'parent' => 0],
    ['id_struct' => 3, 'title' => 'B1', 'parent' => 2],
    ['id_struct' => 4, 'title' => 'B2', 'parent' => 3],
    ['id_struct' => 5, 'title' => 'C', 'parent' => 0],
];

有了这个输出,我需要构建另一个这样的数组:

array (size=3)
  0 => 
    array (size=1)
      'title' => string 'A' (length=1)
  1 => 
    array (size=2)
      'title' => string 'B' (length=1)
      'children' => 
        array (size=1)
          0 => 
            array (size=2)
              'title' => string 'B1' (length=2)
              'children' => 
                array (size=1)
                  0 => 
                    array (size=1)
                      'title' => string 'BB1' (length=3)
  2 => 
    array (size=1)
      'title' => string 'C' (length=1)

它需要是这种格式,这样我才能导出为JSON。

实现这一目标的最佳方式是什么?我找到了很多解决方案,但都是使用print/echo将菜单导出到html,这在这里不起作用。

试试这个:

function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
    if ($element['parent'] == $parentId) {
        $children = buildTree($elements, $element['id_struct']);
        if ($children) {
            $element['children'] = $children;
        }
        $branch[] = $element;
    }
}
 return $branch;
}
$tree = buildTree($output);
echo "<pre>";
print_r( $tree );
echo "</pre>";

希望这能有所帮助。