将类别,子类别和子子类别结构化为多个数组的最佳方法

时间:2016-10-29 15:36:09

标签: php mysql sql codeigniter codeigniter-3

我需要一个帮助来根据名为" products"的表正确构建一个多数组。像这样的结构:

PRODUCTS
+----+------+----------+-------------+----------------+
| id | name | category | subcategory | subsubcategory |
+----+------+----------+-------------+----------------+
| 1  | el1  |    1     |       1     |       5        |
+----+------+----------+-------------+----------------+
| 2  | el2  |    2     |       3     |       1        |
+----+------+----------+-------------+----------------+
| 3  | el3  |    2     |       1     |                |
+----+------+----------+-------------+----------------+

其他表格的结构如下:

CATEGORY

+----+--------+
| id |  name  |
+----+--------+
| 1  |  cat1  |
+----+--------+
| 2  |  cat2  |
+----+--------+
| 3  |  cat3  |
+----+--------+

SUBCATEGORY

+----+-----------+
| id |   name    |
+----+-----------+
| 1  |  subcat1  |
+----+-----------+
| 2  |  subcat2  |
+----+-----------+
| 3  |  subcat3  |
+----+-----------+

SUBSUBCATEGORY

+----+--------------+
| id |     name     |
+----+--------------+
| 1  |  subsubcat1  |
+----+--------------+
| 2  |  subsubcat2  |
+----+--------------+
| 3  |  subsubcat3  |
+----+--------------+

我想要获得的是一个包含所有这些信息的数组,可以轻松访问页面:

Array (
  [0] => Array(
     [id]   => 1
     [name] => cat1

     [subcategory] => Array(
        [0] => Array(
           [id]   => 1
           [name] => subcat1

           [subsubcategory] => Array(
              [0] => Array(
                 [id] => 1
                 [name] => subsubcat1

                 // products here
              )
           )
        )
     )
  )
)

创建一个这样的页面:

<h2>CAT NAME</h2>
   <h3>SUB CAT NAME 1</h3>
       <h4>SUBSUB CAT NAME 5</h4>
            <p>PRODUCT 1</p>
            <p>PRODUCT 5</p>

<h2>CAT NAME 2</h2>
   <h3>SUB CAT NAME 2</h3>
       <p>PRODUCT 2</p>

<h2>CAT NAME 3</h2>
       <p>PRODUCT 3</p>

<h2>CAT NAME 4</h2>
   <h3>SUB CAT NAME 10</h3>
       SUBSUB CAT NAME 2
            <p>PRODUCT 4</p>

0 个答案:

没有答案