从Codeigniter中的数据库查询创建多维数组

时间:2014-01-20 11:31:23

标签: php mysql arrays codeigniter multidimensional-array

我是PHP Codeigniter的新手。我有一个数据库内连接查询,我正在获取类别ID,类别名称,子类别ID和子类别名称,如下所示。

e.g。 enter image description here

我正在找出创建多维数组的方法,其中包含类别ID,名称和子类别详细信息。

e.g。

Array[0]=>Array ( [category_id] => 1 [category_name] => Computer [sub] => 
          Array ([0]=> [subcategory_id] => 1 [subcategory_name] => C Programming ) 
                 [1]=> [subcategory_id] => 2 [subcategory_name] => Website Development) 
                 [2]=> [subcategory_id] => 4 [subcategory_name] => Java)) 

Array[1]=>Array ( [category_id] => 2 [category_name] => Robotics [sub] => 
          Array ( [subcategory_id] => 3 [subcategory_name] => Robo Wars))

由于

2 个答案:

答案 0 :(得分:2)

假设以下是db

的结果数组
$queryResult = array(
  array('category_id'=>1,'category_name'=>'Computer','subcategory_id'=>1,'subcategory_name'=>'C Programming','category_id'=>'1'),
  array('category_id'=>1,'category_name'=>'Computer','subcategory_id'=>2,'subcategory_name'=>'Website Development','category_id'=>'1'),
  array('category_id'=>1,'category_name'=>'Computer','subcategory_id'=>4,'subcategory_name'=>'Java','category_id'=>'1'),
  array('category_id'=>2,'category_name'=>'Robotics','subcategory_id'=>3,'subcategory_name'=>'Robo Wars','category_id'=>'2'),
);

然后你可以试试

$result = array();
foreach($queryResult as $arr){
  $result[$arr['category_id']]['category_id']= $arr['category_id'];
  $result[$arr['category_id']]['category_name'] = $arr['category_name'];
  $result[$arr['category_id']]['sub'][]= array('subcategory_id'=>$arr['subcategory_id'],'subcategory_name'=>$arr['subcategory_name']);
}

希望这是有帮助的

答案 1 :(得分:1)

您没有发布您的查询,但我认为它看起来像这样;

$sql = 'SELECT whatever FROM my_table WHERE category = ?';

$data = array(
    $category
);

$query = $this->db
    ->query( $sql, $data )
    ->result_array();

->result_array()函数添加到查询中将返回关联数组而不是对象。