0

我正在尝试显示存储在我的数据库中的类别:

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
                        )
       )

有谁知道如何做到这一点?我被困在这里,不知道如何创建数组......我知道如何在我的视图中显示它,但让它们进入数组对我来说似乎很难。

提前致谢!

4

3 回答 3

2

这是一个想法:

  1. foreach 类别(4 级除外)检查它是否存在于结果数组中($c
  2. 如果不是,则使用类别名称的标签创建一个数组
  3. 一旦控制类别 2 和 3,您可以在生成的数组中插入最后一个

$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'];
}

这未经测试,但您可以将其用作一个想法

于 2012-05-05T16:55:51.823 回答
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

这个查询只是一个半解决方案,它对你来说并不完美,但你可以从这里开始。

于 2012-05-06T12:07:40.783 回答
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.
}
于 2012-05-05T16:52:48.050 回答