将多维数组从mysql层次表填充到php

时间:2012-09-18 10:27:04

标签: php mysql

我会直接回答这个问题。

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

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

3 个答案:

答案 0 :(得分: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) {
    }
  }
}

答案 1 :(得分: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'];
}

答案 2 :(得分:0)

您必须进行数据库调用才能获得所有类别的列表。

然后你必须使用递归函数将每个类别分配给它的子类别,并且每个子类别分配它的子类别一次又一次(感谢递归这是“简单”)....