该函数的输出看起来不错,但我每次都不知从哪里得到额外的 [0] => Array ( [1] => 1 )
。 id 从我的数据库表中的 1 开始。 0
从哪里出现?!
数组([1] => 数组([name] => Sual [parent] => 0)**[0] => 数组([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
为 null 并且此条件触发:
if (!array_key_exists($parent,$tree)) {
$tree[$parent][$id] = $id;
}
这里$parent
为null,解释为0,这不是$parent
中存在的key(至少不是第一次遇到像这样的一行),所以这导致 $tree[0]
被创建。在您的情况下,parent
为 null 的第一行是 id = 1
的行,因此 $tree[0]
是 数组(1 => 1)
。
将上述条件更改为以下内容:
if (!array_key_exists($parent,$tree) and !is_null($parent)) {
或者如果您的数据库包装器不使用 PHP null
类型来表示 SQL NULL
值,请使用类似这样的东西:
if (!array_key_exists($parent,$tree) and $parent != 0) {
关于php - 函数不知从哪里输出数组 0 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8224076/