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
]

图片转代码服务由CSDN问答提供 功能建议

我有一个数组 $ d_visitors = array_count_values($ d_visitors);

  array:7 [▼
 2 =&gt;  4 
 5 =&gt;  1 
 8 =&gt;  2 
 3 =&gt;  1 
 1 =&gt;  2 
 9 =&gt;  3 
 0 =&gt;  2 
] 
   
 
 

我试图循环遍历该数组24次,并检查密钥是否匹配,并存储其 值。

  $ dv = []; 
for($ i = 0; $ i&lt; 24; $ i ++){
 foreach($ d_visitors as $ k =  &gt; $ v){
 if($ i == $ k){
 $ dv [$ i] = $ v; 
} else {
 $ dv [$ i] = 0; 
} \  n} 
} 
   
 
 

我正在尝试打印出类似这样的内容:

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

但我一直这样:

  array:24 [▼
 0 =  &GT;  2 
 1 =&gt;  0 
 2 =&gt;  0 
 3 =&gt;  0 
 4 =&gt;  0 
 5 =&gt;  0 
 6 =&gt;  0 
 7 =&gt;  0 
 8 =&gt;  0 
 9 =&gt;  0 
 10 =&gt;  0 
 11 =&gt;  0 
 12 =&gt;  0 
 13 =&gt;  0 
 14 =&gt;  0 
 15 =&gt;  0 
 16 =&gt;  0 
 17 =&gt;  0 
 18 =&gt;  0 
 19 =&gt;  0 
 20 =&gt;  0 
 21 =&gt;  0 
 22 =&gt;  0 
 23 =&gt;  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条)

相关推荐 更多相似问题