【问题标题】:Notice: Undefined offset: 0 in while loop注意:未定义的偏移量:while 循环中的 0
【发布时间】:2014-11-24 22:54:38
【问题描述】:

我正在尝试将追随者(在追随者表中)的所有 post_id 放入一个数组中
这可能是一个很长的代码,但这里是:

while (post_count($con, $session_user_id) > $n) {
$pfields = array("post_id", "from", "content", "good", "favorite"/*, "time", "date"*/);
$query = mysqli_query($con, "SELECT followed_id FROM followers WHERE user_id = $session_user_id");
                while($row = mysqli_fetch_assoc($query)) {
                $data = array();
        $data = $row;
    }
    $t = 0;
    $postids = array();
    if (empty($data) !== true && isset($data)) {
        while ($data[$t] !== NULL) { //ERROR HERE
            $sql1 = mysqli_query($con, "SELECT post_id FROM posts WHERE" . $data[$t] . "= from ORDER BY  posts.post_id DESC LIMIT $t, 100") or die(mysqli_error($con));
            while ($row = mysqli_fetch_assoc($sql1)) {
            $postids = array();
            $postids[] = $row[0];
            }
            $t++;
        if ($t>10) {
            break;
        }
        }
    }
    $sql2 = mysqli_query($con, "SELECT post_id FROM posts WHERE from = $session_user_id ORDER BY  posts.post_id DESC LIMIT $n, 100") or die(mysqli_error($con));
    if ($sql2 === false) {
        echo "An error ocurred";
    } else {
    while($row = mysqli_fetch_assoc($sql2)) {
        $postids[] = $row[0]; //ERROR HERE TOO
    }
    }
        rsort($postids); `


显示的错误是注意:未定义的偏移量:0 in /home/cabox/workspace/LOL/home.php 第 55 行 注意:未定义的偏移量:0 在 /home/cabox/workspace/LOL/home。第 72 行的 php
我检查了其他问题,但他们没有回答我自己的问题。我检查了查询,它们确实在我的数据库中显示了一些东西。谢谢!

【问题讨论】:

  • 请正确格式化!我遇到了一些麻烦
  • 将该代码减少到最小的可重现片段。我们甚至不知道第 72 行还是第 55 行。
  • 我在代码中加入了 cmets 来显示第一个和第二个错误的位置

标签: php arrays mysqli while-loop offset


【解决方案1】:

当您使用mysqli_fetch_assoc() 时,结果将被格式化为关联数组。所以你需要改变你的代码如下:

while($row = mysqli_fetch_assoc($sql2)) {
    $postids[] = $row['post_id'];
}

正如PHP的文件所说:

mysqli_fetch_assoc : 获取结果行作为关联数组

否则,您可能需要使用mysqli_fetch_row()

【讨论】:

  • 感谢解决了第二个问题,那么第一个问题呢?
猜你喜欢
  • 1970-01-01
  • 2012-02-08
  • 2015-07-23
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-13
相关资源
最近更新 更多