我在使用多维数组数据时遇到问题。 我加入了2个表(maincategories和类别)。
表主要类别: id,maincategory
表类别: id,maincategory_id,类别
$this->db->select('m.id, m.name_en AS maincategory')
->select('c.name_en AS category')
->from('categories AS c')
->join('maincategories AS m', 'c.maincategory_id=m.id', 'left');
$query = $this->db->get();
这导致所有4个类别如下所列。
[3] => stdClass Object
(
[id] => 7
[maincategory] => Career
[category] => Business Sales
)
[4] => stdClass Object
(
[id] => 1
[maincategory] => Accommodation
[category] => Camping
)
[5] => stdClass Object
(
[id] => 6
[maincategory] => Accommodation
[category] => Hostels
)
[6] => stdClass Object
(
[id] => 7
[maincategory] => Career
[category] => Career Events
)
列表中有4个唯一类别,而 2 属于 maincategory:Accommodaton ,其他 2 类别属于 maincategory:职业。我想要实现的是每个maincategory仅列出ONCE,类别应属于main_category 。像这样:
[6] => stdClass Object
(
[id] => 7
[maincategory] => Career
[category] => array(Career Events, Business Sales, .....)
)
[7] => stdClass Object
(
[id] => 7
[maincategory] => Accommodation
[category] => array(Hostels, Camping, .....)
)
数组转储可能/最终结果可能看起来不同但我希望您了解我想要实现的目标。我读了很多关于转换多维数组的内容。我还是无法理解它。非常感谢任何方向!
答案 0 :(得分:1)
试试这样:
function fetch_all(){
$data = array();
$first = $this->db->select('id, maincategory')->get('maincategory')->result_array();
if( is_array( $first ) && count( $first ) > 0 ){
foreach( $first as $key => $each ){
$data[$key]['category_id'] = $each['id']; #main category id
$data[$key]['maincategory'] = $each['id']; #main category name
$second = $this->db->select('category')->where_in('maincategory_id', $each['id'])->get('categories')->result_array();
$data[$key]['category'] = $second; #all sub-category(s) array
}
}
}
答案 1 :(得分:0)
而不是使用这么多数据库调用,请尝试使用underscore.php库http://brianhaveri.github.io/Underscore.php/
我在这里概述了一些如何使用它的示例:http://codebyjeff.com/blog/2012/08/no-more-machine-gunning-use-underscore-php
修改