How to group posts by category using PHP & MySql? -


i’ve tried using group in query returns 1 post per category. example of returned current setup. need posts same category grouped together, can point me in right direction? time.

like suggested charlotte, group posts in associative array, categories keys.

<?php  // connecting database  $categories = array(); // create empty array while ($post = mysqli_fetch_array($result)) {     if(!array_key_exists($post['category'], $categories)) { // check if category present         $categories[$post['category']] = array(); // create array indexed category name     }     $categories[$post['category']][] = $post; // add post category } ?> 

now have iterate twice : display categories , display each post in category. when have deal nested foreach render html, preferably use inline foreach.

the rendering of posts should :

<?php foreach ($categories $category => $posts) : ?>     <h2><?php echo $category; ?></h2>     <?php foreach ($posts $post) : ?>         <a href='article.php?id=<?php echo $post['post_id']; ?>' ><?php echo $post['title']; ?></a>         <p>posted on <?php echo date('d-m-y h:i:s',strtotime( $post['posted'] ) );?> in <a href='category5.php?id=<?php echo $post['category_id']; ?>' ><?php echo $post['category']; ?></a>         </p>     <?php endforeach; ?>     <hr/> <?php endforeach; ?> 

edit: ometted opening , closing php tags in first block of code. if assemble 2 blocks of code in php file, should work.


Comments