我的模型函数获取论坛未显示正确的顺序或我的父类和子类。
父类别 PHP 应首先位于数组顶部,因为它是类别46的父级,45
问题:如何确保其显示正确的顺序
Array
(
[0] => Array
(
[fid] => 46
[pid] => 41
[name] => password_hash
)
[1] => Array // Parent Category
(
[fid] => 41
[pid] => 0
[name] => PHP
)
[2] => Array
(
[fid] => 45
[pid] => 41
[name] => str_replace
)
)
模型
public function get_forums($pid = '0') {
$categories_data = array();
$this->db->where('pid', $pid);
$this->db->or_where('pid >', $pid);
$this->db->order_by('name', 'asc');
$query = $this->db->get('forum');
foreach ($query->result() as $result) {
$categories_data[] = array(
'fid' => $result->fid,
'pid' => $result->pid,
'name' => $result->name
);
if ($result->pid > 0) {
$category_children[] = $this->make_parent_list($result->pid);
if ($category_children) {
$categories = array_merge($category_children, $categories_data);
}
}
}
return $categories_data;
}
function make_parent_list($fid) {
$forum_data = array();
$forum_query = $this->db->query("SELECT * FROM forum WHERE fid = '" . (int)$fid . "'");
foreach ($forum_query->result() as $forum) {
if ($forum->pid > 0) {
$forum_data[] = array(
'pid' => $forum->pid,
);
$forum_children = $this->make_parent_list($forum->pid);
if ($forum_children) {
$forum_data = array_merge($forum_children, $forum_data);
}
}
}
return $forum_data;
}
答案 0 :(得分:2)
问题在于订购。改变这个
$this->db->order_by('name', 'asc');
有这样的事情:
$this->db->order_by('fid', 'asc');
然后,您也可以按名称对结果进行排序,将其添加为辅助结果:
$this->db->order_by('fid', 'asc');
$this->db->order_by('name', 'asc');