我正在运行一个
mysql查询,结果数组是这样的,每个月都在变化:
Array( [0] => Array ( [day] => 2 [count] => 10 ) [1] => Array ( [day] => 4 [count] => 39 ) [2] => Array ( [day] => 5 [count] => 51 ) )
Array( [0] => Array ( [day] => 1 [count] => 0 ) [1] => Array ( [day] => 2 [count] => 10 ) [2] => Array ( [day] => 3 [count] => 0 ) [3] => Array ( [day] => 4 [count] => 39 ) )
我想用31天填充阵列,使用已经存在的日期和计数数据……就像在第二个例子中那样……第1天和第3天就在那里…所以我添加了它们的数量值0 …按顺序… 1~31天
查询非常简单:
SELECT day(`dates`) day,count(`dates`) count FROM `calls` where month(dates) = 7
所以每个月有不同数量的“天”,有几个月没有电话.
也可以尝试这个,根据您的要求修改范围(1,10)
[akshay@localhost tmp]$cat test.PHP <?PHP $array=array( array("day"=>2,"count"=>10),array("day"=>4,"count"=>39),array("day"=>5,"count"=>51) ); function modify_array($array,$range) { $tmp = array(); array_map(function($_) use (&$tmp){ $tmp[$_] = array("day"=>$_,"count"=>0); },$range); $output = array_combine( array_column($array,"day"),$array ) + $tmp; ksort($output); return array_values($output); } // Output - modify range(1,10) as per your wish print_r( modify_array($array,range(1,10)) ); ?>
产量
[akshay@localhost tmp]$PHP test.PHP Array ( [0] => Array ( [day] => 1 [count] => 0 ) [1] => Array ( [day] => 2 [count] => 10 ) [2] => Array ( [day] => 3 [count] => 0 ) [3] => Array ( [day] => 4 [count] => 39 ) [4] => Array ( [day] => 5 [count] => 51 ) [5] => Array ( [day] => 6 [count] => 0 ) [6] => Array ( [day] => 7 [count] => 0 ) [7] => Array ( [day] => 8 [count] => 0 ) [8] => Array ( [day] => 9 [count] => 0 ) [9] => Array ( [day] => 10 [count] => 0 ) )
– 编辑评论 –
对于没有array_column的旧版PHP
function modify_array($array,$range) { $tmp = array(); array_map(function($_) use (&$tmp){ $tmp[$_] = array("day"=>$_,$range); $output = array_combine( array_map(function($e){return $e["day"];},$array),$array ) + $tmp; ksort($output); return array_values($output); }