Search code examples
phparraysloopsforeachcomparison

How to get iteration count when comparing to arrays in 2 foreach loops using PHP


I have 2 arrays that I would like to get a total vote count for. Array one is user proposals and array 2 is user votes on proposals. I am trying to compare the 2 and count the total votes for each proposal.

Here are the 2 arrays -

$props = json_decode('[{"proposal":"proposal 1", "owner":"tom", "lock_time":1639440607},{"proposal":"proposal 2", "owner":"bob", "lock_time":1639455554}]', true);

$votes = json_decode('[{"vote":"approve", "owner":"tom", "prop-id":1639440607},{"vote":"reject", "owner":"bob", "prop-id":1639455554},{"vote":"reject", "owner":"tom", "prop-id":1639440607}]', true);

The desired output is as follows -

Proposal 1 = 1 Approve and 1 Reject
Proposal 2 = 0 Approve and 1 Reject

The output im getting is -

Proposal 1 = 1 Approve and 1 Reject
Proposal 2 = 1 Approve and 1 Reject

Here is my attempt that is not giving the desired output -

foreach($props as $props){

    $lock_time = $props['lock_time'];
    $my_proposal = $props['proposal'];

    foreach($votes as $votes){

        $id = $votes['prop-id'];
        $vote = $votes['vote'];

        if($lock_time == $id){
           if($vote == 'approve'){
               $yay++;
           }elseif($vote == 'reject'){
               $nay++;
           }
        }
    }

    echo 'Proposal: '.$my_proposal.'<br>';
    echo 'yay:: '.$yay.'<br>';
    echo 'nay:: '.$nay.'<br>';
    echo '<br><br>';

 }

Here is my demo - http://sandbox.onlinephpfunctions.com/code/abea2fa828c067ce3efc1440af201fce839645b6


Solution

  • In this block if($vote == 'approve'){ $yay++; }elseif($vote == 'reject'){ $nay++;}

    you need to reset the values for each proposal , so the could should like this :

    foreach($props as $props){
    
        $lock_time = $props['lock_time'];
        $my_proposal = $props['proposal'];
        $yay=0;
        $nay=0;
        foreach($votes as $vote){
    
            $id = $vote['prop-id'];
            $theVote = $vote['vote'];
    
            if($lock_time == $id){
                if($theVote == 'approve'){
                    $yay++;
                }elseif($theVote == 'reject'){
                    $nay++;
                }
    
            }
        }
        
        echo 'Proposal: '.$my_proposal.PHP_EOL;
        echo 'yay:: '.$yay.PHP_EOL;
        echo 'nay:: '.$nay.PHP_EOL;
        echo PHP_EOL;
    }