1

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;
}
0

1 Answer 1

1

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
);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.