gpt4 book ai didi

php - Yii 中的类别层次结构 (PHP/MySQL)

转载 作者:行者123 更新时间:2023-11-29 12:36:11 24 4
gpt4 key购买 nike

我在这里找到了这个: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 ) )

有人可以找出代码有什么问题并帮助我吗?

最佳答案

你可以试试这个:

$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);

关于php - Yii 中的类别层次结构 (PHP/MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26757267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com