私は質問にまっすぐ行きます。
「id」、「name」、「parent」の3つの列を持つテーブルがあります。各 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) {
}
}
}
方法の 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'];
}
すべてのカテゴリのリストを取得するには、データベース呼び出しを行う必要があります。
次に、再帰関数を使用して、すべてのカテゴリにそのサブカテゴリを割り当て、各サブカテゴリにそのサブカテゴリを何度も割り当てる必要があります (再帰性のおかげで、これは「簡単」です)...