このコードは、以下のデータで正常に機能します。しかし、結果は順序付けられていないlisであり、ドロップダウンコンボボックスとして必要になります。誰かが今投稿のSQLデータと構造でそれを行う方法はありますか?
SQL
CREATE TABLE IF NOT EXISTS `categories` (
`catid` int(3) NOT NULL AUTO_INCREMENT,
`catname` varchar(45) NOT NULL,
`catparent` int(3) NOT NULL,
`catorder` int(4) NOT NULL,
`catdesc` varchar(1024) NOT NULL,
PRIMARY KEY (`catid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`catid`, `catname`, `catparent`, `catorder`, `catdesc`) VALUES
(1, 'Informática', 0, 1000, 'Computadores e acessórios'),
(2, 'Comunicações', 0, 1000, 'Sistemas de Comunicações'),
(3, 'Acessórios', 1, 2000, 'Acessórios para Computadores'),
(4, 'PABX', 2, 2000, 'Centrais telefónicas IP e TDM'),
(5, 'Controle de Acessos', 0, 1000, 'Controle de Acessos e Assiduidade'),
(6, 'Construção Civil', 0, 1000, 'Construçao Civil ');
コード
<?php
include '../lib/configuration.php';
$mysqli = new mysqli($dbhost, $dbuser, $dbpwd, $database);
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM categories";
if ($result = $mysqli->query($query))
{
/* fetch associative array */
while($row = $result->fetch_assoc())
{
$arrayCategories[$row['catid']] = array("pid" => $row['catparent'], "name" => $row['catname']);
}
//createTree($arrayCategories, 0);
function createTree($array, $currentParent, $currLevel = 0, $prevLevel = -1)
{
foreach ($array as $categoryId => $category)
{
if ($currentParent == $category['pid'])
{
if ($currLevel > $prevLevel) echo " <ul> ";
if ($currLevel == $prevLevel) echo " </li> ";
echo '<li id="'.$categoryId.'" onclick=child(this.id);><span>'.$category['name'].'</span>';
if ($currLevel > $prevLevel) { $prevLevel = $currLevel; }
$currLevel++;
createTree ($array, $categoryId, $currLevel, $prevLevel);
$currLevel--;
}
}
if ($currLevel == $prevLevel) echo " </li> </ul> ";
}
?>
<div id="content" class="general-style1">
<?php
if($result->num_rows!=0)
{
?>
<ul>
<li id="0" class="root"><span>Categories</span>
<?php createTree($arrayCategories, 0); ?>
</li>
</ul>
<?php
}
}
?>
</div>