DRY foreach循环与动态变量

时间:2016-04-14 02:06:52

标签: php nested-loops nested-sets

我正在试图找出干燥foreach循环的最佳方法。我需要循环才能将节点添加到树数组中,只要它有任何子节点。

$categories = Category::all();

$nodes = $categories->toTree();

$tree[] = [
    'id' => null,
    'name' => '--No Parent--'
];

foreach ( $nodes as $node ) {

    $tree[] = [
        'id' => $node->id,
        'name' => $node->name
    ];

    foreach ( $node->children as $node2 ) {

        $tree[] = [

            'id' => $node2->id,
            'name' => $node->name.' > '. $node2->name
        ];

    }
}

1 个答案:

答案 0 :(得分:0)

看起来像检查该条件的简单if对您有用。

$categories = Category::all();

$nodes = $categories->toTree();

$tree[] = [
    'id' => null,
    'name' => '--No Parent--'
];

foreach ( $nodes as $node ) {
    if ( is_array($node->children) && count($node->children) > 0 ) {
        $tree[] = [
            'id' => $node->id,
            'name' => $node->name
        ];

        foreach ( $node->children as $node2 ) {

            $tree[] = [

                'id' => $node2->id,
                'name' => $node->name.' > '. $node2->name
            ];

        }
    }
}