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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题