CyberJunkie
CyberJunkie

Reputation: 22684

Multidimensional array from mysql result

I have 2 database tables: categories and sub_categories. sub_categories table is linked to categories table by category id cat_id

In php I want to print the parent category and all the sub-categories belonging to it. Is it possible to do so by creating a multidimensional array from 1 mysql query?

Example result:

array
(
  "Category 1"=>array
  (
  "Sub-category",
  "Sub-category",
  "Sub-category"
  ),
  "Category 2"=>array
  (
  "Sub-category"
  ),
  "Category 3"=>array
  (
  "Sub-category",
  "Sub-category",
  "Sub-category"
  )
 );

My query returns just 1 sub category for each category:

SELECT `categories`.`cat_title`, `sub_categories`.`sub_cat_title` 
FROM (`categories`) 
LEFT JOIN `sub_categories` 
ON `sub_categories`.`cat_id` = `categories`.`cat_id` 
GROUP BY `categories`.`cat_title`

Upvotes: 0

Views: 2105

Answers (2)

dano
dano

Reputation: 1043

MySQL wont return an array, it will only return rows, but you can easily create the array with php.. just do this

<?php
  $db = new mysqli('host','user','password','database');
  $query =  "SELECT c.cat_title, s.sub_cat_title
             FROM categories c
             LEFT JOIN sub_categories s USING (cat_id)
             ORDER BY cat_title";
  $result = $db->query($query);
  while($row = $result->fetch_assoc()){
    $cats[$row['cat_title']][] = $row['sub_cat_title'];
  }        

?>

Upvotes: 3

Carlos Vergara
Carlos Vergara

Reputation: 3622

Try using ORDER BY instead.

ORDER BY `categories`.`cat_title`, `sub_categories`.`sub_cat_title`

Upvotes: 1

Related Questions