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

If you temporarily change the code to this do you see what you would expect to see?

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

I haven’t done that. Let me try that

It assign the last result to all

Try this:


<?php foreach ($votespost as $vp):?>
   <?php if($post->id == $vp->postId):?>

<?php echo '<pre>'. print_r($vp, true) .'</pre>'; ?>

       <li><?=$vp->voteUp . ' Thumb up'?></li>
       <li><?=$vp->voteDown . ' Thumb down'?></li>
   <?php endif;?>
<?php endforeach;?>

Edit:
Notes.

  1. using pre adds linefeeds so the results are easier to read.
  2. the print_r(…) second variable returns a string

Try using var_dump on the compared variables and also maybe trim(…)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.