简体   繁体   中英

foreach loop return a single result set instead of all result

I want to display the number of like and unlike a post has in a forum app. And this is how I create it.

<?php foreach ($votespost as $vp):?>
   <?php if($post->id == $vp->postId):?>
       <li><?=$vp->voteUp . ' Thumb up'?></li>
       <li><?=$vp->voteDown . ' Thumb down'?></li>
   <?php endif;?>
<?php endforeach;?>

But to my surprise, it only displays the result of the last post likes and unlikes(meaning the rest are not shown) and I tried to put this inside a while loop and for loop but dont work as they hang the laptop.

The problem is in the template and not in the controller(so that is why am not showing the controller code)

The $votespost and $post(this is the post of each thread and that display fine) are from the controller class and I think they are working fine

public function viewThread(){
        if (isset($_GET['threadid'])){
            //$thread = $this->threadsTable->findById($_GET['threadid']);
            //$posts = $this->postsTable->find('threadId', $_GET['threadid']);

            foreach ($posts as $post) {
                if($post->id){
                    $votesPost = $this->votesTable->find('postId', $post->id);
                }
            }
        }

        $user = $this->authentication->getUser();

        $title = 'View Topic';
        return [
            'template' => 'viewforum.html.php',
            'title' => $title,
            'variables' => [
                //'thread' => $thread ?? null,
                //'posts' => $posts ?? null,
                'votespost' => $votesPost ?? null,
                //'user' => $user ?? null
            ]
        ];
    }

I have commented out those not useful

<?php foreach ($votespost as $vp):?> <?php if($post->id == $vp->postId):?> <li><?=$vp->voteUp . ' Thumb up'?></li> <li><?=$vp->voteDown . ' Thumb down'?></li> <?php endif;?> <?php endforeach;?>. You have a foreach that iterates all the posts, but inside that you only output if the post id matches the vp postId. You're missing the else case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM