php - Group rows by field -
i have following table structure:
+------------------------+ | id |  name  | category | +------------------------+ |  1 | name_1 |    cat_1 | |  2 | name_2 |    cat_2 | |  3 | name_3 |    cat_1 | |  . |   .    |      .   | |  . |   .    |      .   | |  n | name_n |    cat_k | +------------------------+   were "n" total rows of table , "k" arbitrary number. question is, there way make sql query retrieve rows grouped category? mean possible structure?
array(     "cat_1" => array(                      "name_1", "1",                      "name_3", "3",                ),     "cat_2" => array(                      "name_2", "2",                       rows ....                ),     ...     "cat_k" => array(                      rows....                ), )   if there way please give me keywords, not entire solution please.
you can't in single query since mysql alone not able yield multi-dimensional arrays, it's trivial using php. here do:
$cats = array(); while ($row = $result->fetch()) {     if (!isset($cats[$row->category])) {         $cats[$row->category] = array();     }     $cats[$row->category][] = $row->name; }      
Comments
Post a Comment