我在这里找到了这个:Category Hierarchy (PHP/MySQL)
我想显示该代码,但它无法正常工作。
我得到了以下层次结构:
-Airsoft
--Scopes
这就是全部。但代码显示:
-Airsoft
--Scopes (So far so good)
-Scopes <--- this one should not be here!
以下是代码:
public static function producten(){
$connection=Yii::app()->db; // assuming you have configured a "db" connection
$sql = 'SELECT id, parent, naam FROM categories ORDER BY naam';
$command=$connection->createCommand($sql);
$dataReader=$command->query();
$refs = array();
foreach ($dataReader as $row)
{
$ref = & $refs[$row['id']];
$ref['parent'] = $row['parent'];
$ref['naam'] = $row['naam'];
if ($row['parent'] == NULL)
{
$list[$row['id']] = & $ref;
}
else
{
$refs[$row['parent']]['children'][$row['id']] = & $ref;
}
}
function toUL(array $array)
{
$html = '<ul>' . PHP_EOL;
foreach ($array as $value)
{
$html .= '<li>' . $value['naam'];
if (!empty($value['children']))
{
$html .= toUL($value['children']);
}
$html .= '</li>' . PHP_EOL;
}
$html .= '</ul>' . PHP_EOL;
return $html;
}
print_r($refs);
echo toUL($refs);
}
其中的print_r()
显示:
Array ( [1] => Array ( [parent] => [naam] => Airsoft [children] => Array ( [2] => Array ( [parent] => 1 [naam] => Scopes ) ) ) [2] => Array ( [parent] => 1 [naam] => Scopes ) )
有人可以弄清楚代码有什么问题并帮助我吗?
答案 0 :(得分:1)
你可以试试这个:
$connection=Yii::app()->db; // assuming you have configured a "db" connection
$sql = 'SELECT id, parent, naam FROM categories ORDER BY naam';
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
function createList($elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent'] == $parentId) {
$children = createList($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
$list = createList($dataReader);
CVarDumper::dump($list, 5678, true);