3

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 )  

2 Answers 2

2

Yes, set it in the loop:

$array[ $row['cat_title'] ][ $row['sub_cat_id'] ] = $row['sub_cat_title'];

But, $array[$row['cat_title']] might not be set yet, so you should add this check beforehand:

if( !isset( $array[$row['cat_title']])) {
    $array[$row['cat_title']] = array();
}

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That was easier than I imagined! cat_title will always be set, instead I'm checking if subcategories exist for a category, and displaying them if they exist.
1

You could do something like this:

foreach($array as $key=>$val){
   unset($array[$key]);
   $newKey = //New value

   $array[$newKey] = $val];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.