使用数组时获取foreach错误的无效参数


Getting invalid argument for foreach error when using an array

我不明白为什么会出现这个错误。从我所看到的,我正确使用的函数返回数据库中存在的数据数组。我使用foreach()来回显数组中的每个数据,但它给了我错误:Warning: Invalid argument supplied for foreach() .

函数如下:

// Retrieve posts
    function retrieve_posts(){
        // start new instance of the database connection 
        global $dbh;
        // Get all the posts
        $stmt = $dbh->prepare("SELECT * FROM jacks_barbers_reviews ORDER BY date DESC");
        $stmt->execute();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $result[] = $row;
        }
        return $result;
    }

和(简化的)foreach循环:

<?php
        $posts = retrieve_posts();

            foreach($posts AS $index){
                echo '<div class="test-wrap">'; //contains the individual testimonials
                echo '<p>' . $index['post'] . '</p>';
                echo '<p style="float:right;font-style:normal;font-size:15px;">By ' .$index['name']. '  ' .$index['date']. '</p>';
                echo '<div style="clear:both"></div>';
                echo '</div>'; // closes test-wrap
            }

    ?>

那么是什么导致这个错误呢?

谢谢

我想这可能会发生,如果你没有结果。你没有在retrieve_posts函数中初始化$result变量。返回Null,这是不允许在foreach循环中迭代的值。

尝试在while循环之前初始化变量:$result = array();

编辑:查看所有PHP官方文档:

foreach结构提供了一种简单的方法来遍历数组。Foreach只作用于数组和对象

如果你没有初始化它,你返回一个空值,它既不是一个对象也不是一个数组。