我正在试图找出干燥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
];
}
}
答案 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
];
}
}
}