douyan8961 2015-06-01 17:59
浏览 16
已采纳

数组中的PHP数组

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;
}
  • 写回答

1条回答 默认 最新

  • doujing1156 2015-06-01 18:04
    关注

    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
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染