Jump to content

Foreach loop problem


ANdrww

Recommended Posts

Hello, I have yet another problem I am trying to understand. The thing I don't get is the foreach loop. Here's my code.

 

I have a function to get the posts from the db as follows:

function get_posts($connection) {

	$posts = array();
	$sql = "SELECT * FROM posts ORDER BY stamp DESC";
	$result = mysqli_query($connection, $sql);

	while ($post = mysqli_fetch_object($result)) {
		$posts = array('body' 	 => $post->body,
			       'stamp' 	 => $post->stamp,
			       'post_id' => $post->id,
			       'user_id' => $post->user_id);
		
	}
		return $posts;
}

And I'm (incorrectly) using a foreach loop to display the results like this:

      $posts = get_posts($connection);
      foreach ($posts as $key => $value) {
        echo $posts['body'] . "<hr>";
      }

If I echo $posts['body'] I get the first record showing up 4 times. I've used var_dump($posts) to make sure it's an array, and it is, and it shows the same first record 4 times.

 

Any idea? I'm currently re-reading http://www.php.net/manual/en/control-structures.foreach.php to try and understand this.

 

Thanks, Andrei

Link to comment
https://forums.phpfreaks.com/topic/284730-foreach-loop-problem/
Share on other sites

 

Change

$posts = array('body'   => $post->body,

to

$posts[] = array('body'   => $post->body,

And change the foreach loop to

$posts = get_posts($connection);
foreach ($posts as $post)
{
    echo $post['body'] . "<hr>";
}

Thanks a lot. I knew there was a simple way.

 

Someone on stackoverflow suggested this but couldnt explain to me why he used a foreach loop twice

      foreach($posts as $postInfo) {
          foreach($postInfo as $key => $val) {
            echo '<p>' .$key . ':&nbsp' . $val. '</p>';
   }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.