ANdrww Posted December 12, 2013 Share Posted December 12, 2013 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 Quote Link to comment Share on other sites More sharing options...
Solution Ch0cu3r Posted December 12, 2013 Solution Share Posted December 12, 2013 (edited) 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>"; } Edited December 12, 2013 by Ch0cu3r Quote Link to comment Share on other sites More sharing options...
JIXO Posted December 12, 2013 Share Posted December 12, 2013 Try foreach ($posts as $key => $value) { echo $value . "<hr>"; } Quote Link to comment Share on other sites More sharing options...
ANdrww Posted December 12, 2013 Author Share Posted December 12, 2013 (edited) 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 . ': ' . $val. '</p>'; } } Edited December 12, 2013 by ANdrww Quote Link to comment Share on other sites More sharing options...
Ch0cu3r Posted December 12, 2013 Share Posted December 12, 2013 The first foreach loops through each post array within $posts. The second foreach loops over the elements (body, stamp, post_id, user_id) in the post. Quote Link to comment Share on other sites More sharing options...
ANdrww Posted December 12, 2013 Author Share Posted December 12, 2013 I see. Thanks a lot for the quick replies. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.