Lindsay是一个社交女孩,所以她遇到了很多人,她想整理她的笔记本:
首先是标签,她的名字有点像'学校','工作','派对','在线'等。
在每个标签内,她创建了群组,如:'cool','handy','clingy','good kissers','婚姻材料'等。
在这些群体中实际上是伙伴,每个群体中只有一个。
所以,现在我正在查询数据库,一目了然地向她展示笔记本。
function getNotebook($user_id)
{
// $data[][][] = array(); // declare 3-dimensional array
$sql = "SELECT tab_id, tab_name, tab_color FROM tab WHERE user_id = ?";
$query = $this->db->query($sql, $user_id);
foreach ($query->result() as $row)
{
// ... (put each tab array in the first dimension of $data array)
$sql = "SELECT group_id, group_name, group_size, group_position FROM group WHERE tab_id = ?";
$query2 = $this->db->query($sql, $row->tab_id);
foreach ($query2->result() as $row2)
{
// ... (put each group array in the second dimension of $data)
$sql = "SELECT person_id, person_name, person_gender, person_eye_color FROM person WHERE group_id = ?";
$query3 = $this->db->query($sql, $row2->group_id);
foreach ($query3->result() as $row3)
{
// ... (put each person array in the third dimension of $data)
}
}
}
return $data;
}
我知道在模型中创建HTML并不好,所以我需要保存它(在数组中?)并将其返回到控制器,然后进行建模,我需要通过它来添加HTML标签
功能中的评论是我需要你帮助的地方。
解决方案#2:
将user_id字段添加到person表中,并使用此查询获取所有信息:
$sql = "SELECT * FROM person p
INNER JOIN group g ON g.id = p.group_id
INNER JOIN tab t ON t.id = g.tab_id
WHERE p.user_id = ?
ORDER BY t.id, g.id";
$query = $this->db->query($sql, $user_id);
答案 0 :(得分:2)
function getNotebook($user_id)
{
$data = array(); // not applicable
$sql = "SELECT tab_id, tab_name, tab_color FROM tab WHERE user_id = ?";
$query = $this->db->query($sql, $user_id);
foreach ($query->result() as $row)
{
$temp1 = array(
'id' => $row->tab_id,
'name' => $row->tab_name,
'color' => $row->tab_color,
'groups' => array()
); // create temporary array for storage after loop
$sql = "SELECT group_id, group_name, group_size, group_position FROM group WHERE tab_id = ?";
$query2 = $this->db->query($sql, $row->tab_id);
foreach ($query2->result() as $row2)
{
$temp2 = array(
'id' => $row2->group_id,
'name' => $row2->group_name,
'size' => $row2->group_size,
'position' => $row2->group_position,
'people' => array()
); // create another temporary array for storage after loop for second dimension
$sql = "SELECT person_id, person_name, person_gender, person_eye_color FROM person WHERE group_id = ?";
$query3 = $this->db->query($sql, $row2->group_id);
foreach ($query3->result() as $row3)
{
$temp2['people'][] = array(
'name' => $row3->person_name,
'gender' => $row3->person_gender,
'eye_color' => $row3->person_eye_color
); // store data
}
$temp1['groups'][] = $temp2; // store temp array
}
$data[] = $temp1; // store temp array
}
return $data;
}
这就是你要找的东西吗?