函数的输出看起来不错,但我每次都从任何地方获得额外的[0] => Array ( [1] => 1 )
。id从我的db表中的1开始。0
是从哪里来的?!
Array ( [1] => Array ( [name] => Sual [parent] => 0 ) **[0] => Array ( [1] => 1 )** ...
函数
<?php
function treeGen($menu, $utype) {
global $db;
$tree = array();
$stmt = $db->prepare("select id, parent, name FROM navigation WHERE menu=? AND user_type=?") or die($db->error);
$stmt->bind_param("ii", $menu, $utype) or die($stmt->error);
$stmt->execute() or die($stmt->error);
$stmt->store_result();
$meta = $stmt->result_metadata();
$stmt->bind_result($id, $parent, $name);
while ($stmt->fetch()) {
$tree[$id] = array(
'name' => $name,
'parent' => $parent
);
if (!array_key_exists($parent,$tree)) {
$tree[$parent][$id] = $id;
}
}
$stmt->close();
print_r($tree);
}
?>
我想当您遇到表中的顶级行(没有父行)时,问题就出现了。当您处理其中一行时,$parent
为空,并触发此条件:
if (!array_key_exists($parent,$tree)) {
$tree[$parent][$id] = $id;
}
这里$parent
为null,它被解释为0,这不是$parent
中存在的键(至少,不是您第一次遇到这样的行),因此这导致创建$tree[0]
。在您的示例中,parent
为空的第一行是id = 1
的行,因此$tree[0]
为array(1 => 1)
。
将上述条件改为:
if (!array_key_exists($parent,$tree) and !is_null($parent)) {
或者如果您的DB包装器不使用PHP null
类型来表示SQL NULL
值,则使用如下内容:
if (!array_key_exists($parent,$tree) and $parent != 0) {
if (!array_key_exists($parent,$tree)) {
$tree[$parent][$id] = $id;
我认为。尝试注释这段代码,然后打印数组$tree