1

我直接回答这个问题。

我有一张桌子,有 3 列:“id”、“name”和“parent”。每个 id 代表类别,而 parent 是引用子类别的 id。

我需要构建一个菜单,因此,一个无序列表和嵌套的无序列表。我得出的结论是,我必须将其转换为数组,是否有另一种仅使用 mysql 的方法?如果没有,你能告诉我在 php 中构建多维数组的技术吗?

4

3 回答 3

2

我想出了另一个不使用递归的代码:

<?php
//Let's say the DB returns:
$categories = array(
    array( 'id' => 1, 'name' => 'Category 1', 'parent' => null ),
    array( 'id' => 2, 'name' => 'Category 2', 'parent' => null ),
    array( 'id' => 3, 'name' => 'Category 3', 'parent' => 1 ),
    array( 'id' => 4, 'name' => 'Category 4', 'parent' => 3)
    );


$sortedCategories = assignChildren( $categories );

function assignChildren( &$categories )
{
    $sortedCategories = array();
    foreach( $categories as &$category )
    {
        if ( !isset( $category['children'] ) )
        {
            // set the children
            $category['children'] = array();
            foreach( $categories as &$subcategory )
            {
                if( $category['id'] == $subcategory['parent'] )
                {
                    $category['children'][] = &$subcategory;
                }
            }
        }

        if ( is_null( $category['parent'] ) )
        {
            $sortedCategories[] = &$category;
        }

    }

    return $sortedCategories;
}

var_dump( $sortedCategories );

输出:

array(2) {
  [0]=>
  &array(4) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(10) "Category 1"
    ["parent"]=>
    NULL
    ["children"]=>
    array(1) {
      [0]=>
      &array(4) {
        ["id"]=>
        int(3)
        ["name"]=>
        string(10) "Category 3"
        ["parent"]=>
        int(1)
        ["children"]=>
        array(1) {
          [0]=>
          &array(4) {
            ["id"]=>
            int(4)
            ["name"]=>
            string(10) "Category 4"
            ["parent"]=>
            int(3)
            ["children"]=>
            array(0) {
            }
          }
        }
      }
    }
  }
  [1]=>
  &array(4) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(10) "Category 2"
    ["parent"]=>
    NULL
    ["children"]=>
    array(0) {
    }
  }
}
于 2012-09-18T13:02:48.143 回答
1

一种方法是准备您的多维数组,如下所示......它可能不是完美的,但它对我来说效果很好......

$result_category = mysql_query('select all records query here ...');
    $categoryData = array(
    'items' => array(),
    'parents' => array()
);

while ($categoryItem = mysql_fetch_assoc($result_category))
{
    $categoryData['items'][$categoryItem['category_id']] = $categoryItem;
    $categoryData['parents'][$categoryItem['parent_id']][] = $categoryItem['category_id'];
}
于 2012-09-18T10:33:53.533 回答
0

您必须进行数据库调用以获取所有类别的列表。

然后,您必须使用递归函数为每个类别分配其子类别,并一次又一次地为每个子类别分配其子类别(感谢递归,这很“容易”)......

于 2012-09-18T10:34:30.723 回答