Search code examples
phparraysforeach

Nested loop only returns data from the last iteration


Can someone explain to me why this isn't working? I'm trying to push an array into another array, but its only coming back with the last item from the $votes array.

foreach($json['area'] as $row) {
    $name = $row['name'];
    $group = $row['array']['group'];
    $majority = $row['array']['majority'];
    $candidates = $row['array']['candidates'];
    foreach ($candidates as $candidate) {
        $vote = $candidate["votes"];
        $candi = $candidate["name"];
        $votes = array("vote" => $vote, "candidate" => $candi);
    }
    $array = array("name" => $name, "group" => $group, "majority" => $majority, "votes" => $votes);

    $results[] = $array;
}

Solution

  • Each iteration of the outer loop is only producing a single $votes array , seemingly for a single candidate, in this line:

    $votes = array("vote" => $vote, "candidate" => $candi);
    

    If you want to capture multiple entries in that array for each row, you need to make it a multi-dimensional array also:

    $candidates = $row['array']['candidates'];
    $votes = [];
    foreach ($candidates as $candidate) {
        $votes[] = array(
            "vote"      => $candidate["votes"], 
            "candidate" => $candidate["name"]
        );
    }
    
    $array = array(
        "name"     => $name, 
        "group"    => $group, 
        "majority" => $majority, 
        "votes"    => $votes
    );