【发布时间】:2017-10-28 15:46:34
【问题描述】:
我有一个数组输出是这样的树状结构:
在这里,我有一个具有父子关系的数据库表,例如:
public function up()
{
Schema::create('trees', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id')->unsigned()->nullable();
$table->string('name');
$table->integer('has_child');
$table->integer('depth');
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('trees')->onDelete('cascade');
}
}
这里,
深度定义树中从根开始的深度,parent_id 指同一张表中的父级,has_child 定义子级的存在。对于叶子,has_child 为零,而顶部 parent_id 为空。
深度可以是最大为 5 的任何值。 在上述情况下,只有 2 个用于测试目的。
这是我的示例数据库记录:
我在控制器中递归地得到了上面的树结构:
public function getChilds($d){
$tree = array();
$children = array();
$tree['parent'] = $d->toArray();
if($d->has_child==1){
$data = Tree::where('parent_id',$d->id)->get();
foreach ($data as $d) {
$first = $this->getChilds($d);
array_push($children, $first);
}
}
$tree['children'] = $children;
return $tree;
}
public function getTree(){
$tree = array();
$data = Tree::where('parent_id',null)->get();
foreach ($data as $d) {
$first = $this->getChilds($d);
array_push($tree, $first);
}
return view('tree',compact('tree'));
}
现在,
我想在树状结构中显示这些数据。但是,由于深度不同,我无法确定我应该去的深度。
有什么方法可以在 laravel Blade 中递归显示这个结构?
预期的输出是这样的:
One0
One0Two0
One0Two0Three0
One0Two0Three1
One0Two1
One0Two1Three0
One0Two1Three1
One0Two2
One0Two2Three0
One0Two2Three1
感谢任何形式的帮助。
【问题讨论】: