PHP - Warning: Invalid argument supplied for foreach()

时间:2017-07-12 08:20:39

标签: php html arrays

I did look up this error and people say that it is caused by an empty array, but as you can see, I have entries for my array. Or that the variable isn't an array, which it is. I am unsure as to why this doesn't work. Any help would be greatly appreciated.

<? php 
    $posts = array();
    $posts[0] = array(
        'user' => 'Bob',
        'message' => 'This is a post',
        'image' => 'image/picture.jpg',
        'date' => '20/4/17');
    $posts[1] = array(
        'user' => 'James',
        'message' => 'This is also a post',
        'image' => 'image/picture.jpg',
        'date' => '20/4/15');
    $posts[2] = array(
        'user' => 'Steve',
        'message' => 'This is also also a post',
        'image' => 'image/picture.jpg',
        'date' => '20/4/13');

?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Social Media</title>
    <link rel="stylesheet" href="style/style.css">
  </head>
  <body>
    <h1> Social Media </h1>
    <?php foreach ($posts as $post){?>
    <p>
        <?= $post['user'] ?>
        <?= $post['message'] ?>
        <?= $post['date'] ?>
        <?= $post['image'] ?>
    </p>
    <?php } ?>

  </body>
</html>

3 个答案:

答案 0 :(得分:0)

您有阵列数组,您必须指定要回显的数组值,

echo $post[0]['user'];

它将从$posts[0]打印用户。

<?php
 $c = 0;
 foreach ($posts as $post){?>
<p>
    <?= $post[$c]['user'] ?>
    <?= $post[$c]['message'] ?>
    <?= $post[$c]['date'] ?>
    <?= $post[$c]['image'] ?>
</p>
<?php
$c++;
 } ?>

答案 1 :(得分:0)

我实际测试了上面的代码并且我没有看到您的代码有任何问题,但可能您已将所有error_reporting转换为E_ALL或其他东西,但无论如何您可以在下面尝试,请务必检查是否对象是否为数组

if (is_array($posts)) 
{
  foreach ($posts as $post)
  {
       //do something
   }
}

答案 2 :(得分:0)

@mim。注意到在开放的php标签中有一个杂散空间,删除它修复了这个问题。