简体   繁体   English

foreach循环返回单个结果集,而不是所有结果

[英]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. 但是令我惊讶的是,它只显示了上一个帖子喜欢和不喜欢的结果(意味着其余帖子未显示),我试图将其放入while循环和for循环内,但由于它们挂起笔记本电脑而无法正常工作。

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 $ votespost和$ post(这是每个线程的帖子,显示效果很好)都来自控制器类,我认为它们工作正常

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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