用于对类别和子类别进行分组的多维数组 [英] Multidimensional array to group Categories and sub-categories

查看:56
本文介绍了用于对类别和子类别进行分组的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to group subcateogries within categories. The subcategories can have any number of elements such as this:

输出:

category #1
    item 1 
    item 2
    item 3

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

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

My initial plan is to use a multidimensional array like this:

$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',

    ...
),
....
);

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

My code so far...

$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. 如何在多维数组中选择类别并将它们放入自己的数组中?

  1. How do I select categories and put them into their own arrays within a multidimensional array?

然后如何将子类别放入适当的类别数组中?

How do I then put the subcategories inside the appropriate category arrays?

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

And last, how do I print out an entire multidimensional array that can have any number of subcategories?

推荐答案

您应该首先获得一个查询的所有子类别和类别:

You should first get all the subcategories and categories on one queries:

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);

这篇关于用于对类别和子类别进行分组的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆