嵌套循环仅返回上次迭代的数据

问题描述 投票:0回答:1

有人可以向我解释为什么这不起作用吗?我正在尝试将一个数组推入另一个数组,但它只返回 $votes 数组中的最后一项。

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;
}
php arrays foreach
1个回答
1
投票

外循环的每次迭代仅生成一个

$votes
数组,看起来是针对单个候选者,在这一行中:

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

如果您想捕获该数组中每一行的多个条目,则还需要将其设为多维数组:

$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
);
© www.soinside.com 2019 - 2024. All rights reserved.