Jump to content

Foreach loop problem


ANdrww
Go to solution Solved by Ch0cu3r,

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
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>';
   }
}
Edited by ANdrww
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.