dongqi0644 2017-03-18 23:01
浏览 118
已采纳

为什么在foreach中更新时数组中的值不会更改?

I am stuck with getting a change in an specific value in an array.

The following is the relevant code I use in the moment:

$countryCountList=array("Italy"=> 0, "USA"=> 0);

$localResult=mysqli_query($con, $queryforcheck) or die("Errormessage: %s
". $con->error);
        $wholeCountryArray = $localResult->fetch_array(MYSQLI_NUM);

foreach($wholeCountryArray as $rowCountry) {
            $countryCountList[$rowCountry]=$countryCountList[$rowCountry]+1;
            }

return $countryCountList;

So I want to count some values in the array "countryCountList" up in the foreach-loop. I can proof that the foreach is counting, but when it comes to the return at the end of my php-file it returns the values that where defined in the first line of this snippet of code.

So it seems that foreach does counting the values of the array up but doesn´t save it to return it succesfully.

Hope this is enough information. Anybody an idea?

  • 写回答

1条回答 默认 最新

  • dongqian5384 2017-03-18 23:18
    关注

    Try replacing MYSQLI_NUM with MYSQLI_ASSOC

    $wholeCountryArray = $localResult->fetch_array(MYSQLI_ASSOC);
    

    Your loop is probably running, but rather than having the string indices that you're expecting it's just using numbers, and so it's doing

    $countryCountList[0]=$countryCountList[0]+1;
    

    rather than

    $countryCountList["Italy"]=$countryCountList["Italy"]+1;
    

    like you're thinking it is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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