用于对类别和子类别进行分组的多维数组

时间:2012-12-01 02:02:24

标签: php mysql

我想在类别中对子类别进行分组。子类别可以包含任意数量的元素,例如:

输出:

category #1
    item 1 
    item 2
    item 3

category #2
   item 1 
   item 2
   item 3
   item 4
   item 5

我最初的计划是使用像这样的多维数组:

$categories = array(
'cateogy_name_1' => array(
    1 => 'item_1',
    2 => 'item_2',
    ...
),
'cateogy_name_2' => array(
    1 => 'item_1',
    2 => 'item_2',
    3 => 'item_3',
    4 => 'item_4',
    5 => 'item_5',

    ...
),
....
);

我的代码到目前为止......

$categories = array();
$result= mysql_query("SELECT category_id, product_name  FROM `table` GROUP BY     
`catagory_id` ORDER BY `catagory_id`");  //retreive all categories and sub-categories

while($row = mysql_fetch_array($result))
 {
    //Get Categories and create arrays inside a single array
    //I'm stuck here, not sure how to initialize the multi-dimensional array
 }

foreach // Put all subcategories within the correct categories

        // I'm stuck here. How would I get the subcategories and put 
        // them into the correct category?

好的,我的问题是:

  1. 如何在多维数组中选择类别并将它们放入自己的数组中?

  2. 如何将子类别放在适当的类别数组中?

  3. 最后,如何打印出可以包含任意数量子类别的整个多维数组?

2 个答案:

答案 0 :(得分:2)

首先应该在一个查询中获取所有子类别和类别:

SQL:

SELECT     sub_category_id, 
           category_id,
           sub_category_name,
           category_name           
FROM       sub_categories a
INNER JOIN categories b
    ON     a.category_id=b.category_id

PHP:

$categories = array();
while ($row = mysql_fetch_assoc($result)) {
    $cat_name = $row['category_name'];
    $sub_cat_id = $row['sub_category_id'];
    $sub_cat_name = $row['sub_category_name'];
    $categories[$cat_name][$sub_cat_id] = $sub_cat_name;
}

var_dump($categories);

答案 1 :(得分:0)

注意:您不应使用已弃用的mysql_*函数。请改用PDO或类似内容。

$categories = array();
while($row = mysql_fetch_assoc($result))
{
    $cat = $row['category_id'];
    $categories[$cat][] = $row['product_name'];
}

喜欢那个?