douguan3470 2016-04-04 14:11
浏览 64
已采纳

如何使用默认值数组和新值数组生成数组?

I have an array $d_visitors = array_count_values($d_visitors);

array:7 [▼
  2 => 4
  5 => 1
  8 => 2
  3 => 1
  1 => 2
  9 => 3
  0 => 2
]

I'm trying to loop through that array 24 times, and check if the key matches, and store its value.

$dv = [];
for ($i = 0; $i < 24; $i++){
    foreach ($d_visitors as $k =>$v) {
        if($i == $k ){
            $dv[$i] = $v;
        }else{
            $dv[$i] = 0;
        }
    }
}

I'm trying to print out something like this:

array:24 [▼
  0 => 2
  1 => 2
  2 => 4
  3 => 1
  4 => 0
  5 => 1
  6 => 0
  7 => 0
  8 => 2
  9 => 3
  10 => 0
  11 => 0
  12 => 0
  13 => 0
  14 => 0
  15 => 0
  16 => 0
  17 => 0
  18 => 0
  19 => 0
  20 => 0
  21 => 0
  22 => 0
  23 => 0
]

But I kept getting this:

array:24 [▼
  0 => 2
  1 => 0
  2 => 0
  3 => 0
  4 => 0
  5 => 0
  6 => 0
  7 => 0
  8 => 0
  9 => 0
  10 => 0
  11 => 0
  12 => 0
  13 => 0
  14 => 0
  15 => 0
  16 => 0
  17 => 0
  18 => 0
  19 => 0
  20 => 0
  21 => 0
  22 => 0
  23 => 0
]
  • 写回答

3条回答 默认 最新

  • duanji7881 2016-04-04 14:13
    关注

    Try this way:

    $dv = [];
    for ($i = 0; $i < 24; $i++){
        $dv[$i] = 0;
        if (isset($d_visitors[$i])) {
            $dv[$i] = $d_visitors[$i];
        }
    }
    

    More simplified is:

    $dv = [];
    for ($i = 0; $i < 24; $i++){
        $dv[$i] = isset($d_visitors[$i])? $d_visitors[$i] : 0;
    }
    

    The problem in your code is in line $dv[$i] = 0; as it sets to zero $dv[$i] which earlier has been set.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?