php - 函数不知从哪里输出数组 0 个元素

标签 php mysql arrays prepared-statement

该函数的输出看起来不错,但我每次都不知从哪里得到额外的 [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/

相关文章:

php - 未知列 "in field list form "

mysql - 如何在 MySQL 用户名中使用动态 DNS 名称?

javascript - 从 jQuery.each 中删除元素会弄乱循环吗?

c# - C# 中的计算数组值 - 响应式(Reactive)编程

javascript - CSS - 使用悬停以不同方式影响多个元素

php - 如何在 PHP 中获取图像质量

javascript - 结合多种表单的ajax代码

php - 在mysql数据库中存储日期

mysql - mysql存储过程中的嵌套循环

javascript - 数组 forEach 传递 "push"作为参数