I’m using a single mysql query to create a multidimensional array for nested results (categories and subcategories).
Query
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
Creating multidimensional array
$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;
The above returns categories and and their respective subcategories.
Array (
[Art] => Array ( [0] => Graphic Design [1] => Painting )
[Literature] => Array ( [0] => Science Fiction [1] => Poetry [2] => Fiction )
[Science] => Array ( [0] => Environmental )
)
Is it possible to replace the array keys with query data like the subcategory id sub_cat_id? For example
[Literature] => Array ( [8] => Science Fiction [94] => Poetry [5] => Fiction )
Yes, set it in the loop:
But,
$array[$row['cat_title']]might not be set yet, so you should add this check beforehand:Your original code doesn’t need this check since
$array[]will not generate any notices/warnings, but when you try to set a specific key, that will generate a notice/warning if the variable isn’t already declared as an array.