简体   繁体   English

数组内的PHP数组

[英]PHP array within array

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. 我正在尝试将一个数组推入另一个数组,但是它只与$ 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;
}

Each iteration of the outer loop is only producing a single $votes array , seemingly for a single candidate, in this line: 外循环的每次迭代仅生成一个$votes数组,似乎是针对单个候选者,在此行中:

$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
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM