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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀