簡體   English   中英

從mysql層次結構表向php填充多維數組

[英]populating multidimensional array from mysql hieararchy table to php

我直接問這個問題。

我有一個表,其中包含3列:“ id”,“ name”和“ parent”。 每個id代表類別,父代是引用子類別的id。

我需要構建一個菜單,因此需要一個無序列表和嵌套的無序列表。 我得出的結論是我必須將其轉換為數組,是否有另一種方法僅使用mysql; 如果不能,那么您能否指示我在php中構建多維數組的技術?

我想出了另一個不使用遞歸的代碼:

<?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) {
    }
  }
}

一種方法是如下准備多維數組...可能不是完美的方法,但對我來說效果很好...

$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'];
}

您必須進行數據庫調用才能獲得所有類別的列表。

然后,您必須使用遞歸函數一次又一次地為每個類別分配其子類別,並為每個子類別分配其子類別(由於遞歸,這很“容易”)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM