douniuta4783 2015-08-12 08:00
浏览 103
已采纳

将值添加到同一个数组键中

I'm sure this is a silly question, but I don't understand the reason. Why I cannot add values into the same array key? The values were overwritten.

$rows=array();
while($row = mysqli_fetch_array($result)) {
    $rows[strval($row['year'])]=array('month'=>$row['month'],'satisfaction'=>$row['sat_per_month']);
}
  • 写回答

4条回答 默认 最新

  • doudan5136 2015-08-12 08:15
    关注

    In PHP (and almost all programming languages) array indexes are unique. This means that $arr["teletubbies"] cannot be "lala" and "noonoo" at the same time. This is for the simple reason that if you would call $arr["teletubbies"] at a later time PHP cannot know whether you meant "lala" or "noonoo" then.

    To solve this issue (you want some things ordered by their year, e.g. 2014) it is advisable to make the value correlated to key 2014 a new array, thus creating a multidimensional array. You seem to understand that, but your implementation is wrong, as you are now just changing $rows[strval($row['year'])] to something new instead of appending the new values.

    There are multiple solutions to this problem to do so:

    Solution 1:

    $rows=array();
    while($row = mysqli_fetch_array($result)) {
        //The syntax [] means: insert after the last defined key, more information at: http://php.net/manual/en/language.types.array.php look for $arr[] = 56;
        $rows[strval($row['year'])][] = array('month'=>$row['month'],'satisfaction'=>$row['sat_per_month']);
    }
    

    Solution 2:

    $rows=array();
    while($row = mysqli_fetch_array($result)) {
        //Make sure $rows[strval($row['year'])] is an array
        if (!isset($rows[strval($row['year'])])) $rows[strval($row['year'])] = Array();
        //array_push pushes a new array element to the last element of an array, documentation here: http://php.net/manual/en/function.array-push.php
        array_push($rows[strval($row['year'])],array('month'=>$row['month'],'satisfaction'=>$row['sat_per_month']));
    }
    

    There are probably several other solutions aswell, but you get the idea.

    To call one of the $rows[strval($row['year'])] later, you must make sure you call the newly created indexes! For example:

    //Three indexes! 1st is the year, 2nd is the nth child you added and third is Array("month" => "..", "satisfaction" => "...");
    print_r($rows["2014"][5]);
    

    or

    echo $rows["2014"][3]["month"]." ".$rows["2014"][3]["satisfaction"];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图