我正在使用单个 mysql 查询为嵌套结果(类别和子类别)创建多维数组。
询问
SELECT `categories`.`cat_title`, `subcategories`.`sub_cat_id`, `subcategories`.`sub_cat_title`
FROM (`categories`)
LEFT JOIN `subcategories`
ON `subcategories`.`cat_id` = `categories`.`cat_id`
ORDER BY `categories`.`cat_title
创建多维数组
$array = array();
foreach ($query->result_array() as $row): //query result as a pure array
$array[$row['cat_title']][] = $row['sub_cat_title'];
endforeach;
return $array;
以上返回类别及其各自的子类别。
Array (
[Art] => Array ( [0] => Graphic Design [1] => Painting )
[Literature] => Array ( [0] => Science Fiction [1] => Poetry [2] => Fiction )
[Science] => Array ( [0] => Environmental )
)
是否可以用子类别 id 之类的查询数据替换数组键sub_cat_id
?例如
[Literature] => Array ( [8] => Science Fiction [94] => Poetry [5] => Fiction )