我正在尝试显示存储在我的数据库中的类别:
http://dl.dropbox.com/u/16459516/Screen%20shot%202012-05-05%20at%2015.59.40.png
我的想法是在我的模型中从数据库中获取所有数据,并在我的函数中重建数组:
function get_all_categories() {
$query = $this->db->query('SELECT * FROM categories');
//code to reconstruct my array like:
//foreach($query->result_array() as $row) {
//$categories[$row['niveau_1']] = array[]
//}
return $categories;
}
并输出一些数组,如:
[0] => Array
(
[niveau_1] => main category name
[niveau_2] => Array(
...children here and children of these childs
)
)
有谁知道怎么做?我卡在这里,不知道如何创建阵列...我知道如何在我的视图中显示它,但在阵列中获取它们对我来说似乎很难。
提前致谢!
答案 0 :(得分:2)
这是一个想法:
$c
)$ query = $ this-> db-> query('SELECT * FROM categories');
$raw_categories = $query->result_array();
$c = array();
foreach($raw_categories AS $row)
{
if(!array_key_exists($row['niveau_2'],$c) && !empty($row['niveau_2']))
{
$c[$row['niveau_2']] = array();
}
if(!array_key_exists($row['niveau_3'],$c[$row['niveau_2']]) &&
!empty($row['niveau_3']))
{
$c[$row['niveau_2']]['niveau_3'] = array();
}
$c[$row['niveau_2']]['niveau_3'][] = $row['niveau_4'];
}
这未经过测试,但您可以将其用作想法
答案 1 :(得分:1)
我认为你的数据库错了。据我所知,这是一个“内容表”或类似内容(类别,子类别,子子类别等)。 “1. Visie,Beleid ......”出现了很多次。
如果我要更改数据库:
table niveau_1
id_1 - primary key
title - string
table niveau_2
id_2 - primary key
id_1 - connect to niveau_1 (which niveau_1 is its 'parent')
title - string
table niveau_3
id_3 - primary key
id_2 - connect to niveau_2 (which niveau_2 is its parent)
title - string
在这种情况下,在您的数据库中不会重复元素,我认为您想要的查询将更简单:
SELECT
niveau_1.title AS title_1,
GROUP_CONCAT(niveau_2.title,"@") AS title_2,
GROUP_CONCAT(niveau_3.title,"@") AS title_3
FROM niveau_1
LEFT JOIN niveau_2 ON niveau_2.id_1=niveau_1.id_1
LEFT JOIN niveau_3 ON niveau_3.id_2=niveau_2.id_2
GROUP BY niveau_2.id_2
这个查询只是一个半解决方案,它不适合你,但你可以从这里开始。
答案 2 :(得分:0)
// your model using activerecord
public function getCategories(){
$q = $this->db->get('categories');
if($q->num_rows > 0){
return $q->result();
}else{
return false;
}
}
//your controller
$this->load->model('category_model');
$data['results'] = $this->category_model->getCategories();
foreach($data['results'] as $c){
//iterate through categories, match them to points.
//match category_id in results with category_id in the other table results
//setup a multi dimensional array to build up what you need.
}