【发布时间】:2014-11-05 12:30:25
【问题描述】:
我在这里找到了这个: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 ) )
有人可以找出代码有什么问题并帮助我吗?
【问题讨论】:
-
尝试添加 GROUP BY naam
-
@Naruto 没有区别 :(
-
那么问题是,您没有检查该父母的孩子是否已经存在..
-
@Naruto 好吧.. 你有/知道解决方法吗?
-
未测试,但类似: if(!(in_array($row['parent'], $refs){ $refs[$row['parent']]['children'][ $row['id']] = & $ref; }
标签: php mysql yii categories hierarchy