duanhuan5409 2018-11-24 23:18
浏览 212

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

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

  • 写回答

1条回答 默认 最新

  • duanche8554 2018-11-25 00:26
    关注
    <?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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?