我想实现这种结构
[
{
"leader":"leader1",
"subs":[
{
"sub":"sub1",
"members":[
"mem1",
"mem2"
]
},
{
"sub":"sub2",
"members":[
"mem3"
]
}
]
},
{
"leader":"leader2",
"subs":[
{
"sub":"sub3",
"members":[
"mem4",
"mem5"
]
}
]
}
]
我有两种实现此目标的方法。
我的目标是产生最快的东西。
1。多个Foreach
我正在使用codeigniter,并且正在为每个函数调用/执行SELECT
。这实际上是在执行多个选择以生成结果。
$data = array();
foreach($this->whatever_model->get_leaders() as ldr) {
$subs = $this->whatever_model->get_subs($ldr['id']);
foreach ($subs as $sub) {
$sub['members'] = $this->whatever_model->get_members($sub['id']);
$ldr['subs'] = $sub;
}
$data[] = $ldr;
}
return $data;
2。重建阵列-单一查询
我还记得只有一个查询。选择所有将具有以下结果的成员:
[
{
"member":"mem1",
"sub":"sub1",
"leader":"leader1"
},
{
"member":"mem2",
"sub":"sub1",
"leader":"leader1"
},
{
"member":"mem3",
"sub":"sub2",
"leader":"leader1"
},
{
"member":"mem4",
"sub":"sub3",
"leader":"leader2"
},
{
"member":"mem5",
"sub":"sub3",
"leader":"leader2"
}
]
然后将结果重建为不同的结构。
问题: