在PHP中,我想构建一个数组,该数组使用不同的$raw['day']
作为每一行,并计算所有大于0的$raw['delay']
:
开始
$raw = array(
[0] => ("day" => "2013-01-01", "delay" => 3),
[1] => ("day" => "2013-01-01", "delay" => 16),
[2] => ("day" => "2013-01-01", "delay" => 0),
[3] => ("day" => "2013-01-02", "delay" => 1),
[4] => ("day" => "2013-01-02", "delay" => 0),
[5] => ("day" => "2013-01-03", "delay" => 9),
);
结果
array(
[0] => ("day" => "2013-01-01", "misses" => 2),
[1] => ("day" => "2013-01-02", "misses" => 1),
[2] => ("day" => "2013-01-02", "misses" => 1),
)
我尝试了什么:
我首先想到的是,我将获得所有独特的日子:
$all_days = array_column($raw, 'day');
$unique_days = array_unique($all_days);
现在我已经度过了所有独特的日子,我可以再次遍历$raw
并增加未命中率。但这似乎过于冗长,我认为在PHP的数组函数中会有一个更简单的解决方案。
foreach ($raw as $row) {
if ($row['delay'] > 0) {
$unique_days[$row['day']]++
}
}
答案 0 :(得分:0)
你可以使用array_walk函数,但我想你唯一需要的是:
$unique_days = array();
foreach ($raw as $row) {
if (!isset($unique_days[$row['day']])) $unique_days[$row['day']] = 0; -- place 1
if ($row['delay'] > 0) {
if (!isset($unique_days[$row['day']])) $unique_days[$row['day']] = 0; -- place 2
$unique_days[$row['day']]++
}
}
它只存储具有适当计数器的唯一日子
更新检查位置1和2 - 如果您需要最终阵列中的所有日期,则需要第一个,如果您只需要独特的日子且不需要警告,则需要第二个
答案 1 :(得分:0)
这是一种可行的方法:
$sum=array();
foreach ($raw as $r) {
if ($r["delay"]>0) $sum[$r["day"]]++;
}
然后
foreach ($a as $k => $v) {
$sum[]=array("day"=>$k, "misses" => $v);
}
print_r($sum);
$raw = array(
0 => array("day" => "2013-01-01", "delay" => 3),
1 => array("day" => "2013-01-01", "delay" => 16),
2 => array("day" => "2013-01-01", "delay" => 0),
3 => array("day" => "2013-01-02", "delay" => 1),
4 => array("day" => "2013-01-02", "delay" => 0),
5 => array("day" => "2013-01-03", "delay" => 9),
);
$a=array();
foreach ($raw as $r) {
if ($r["delay"]>0) {$a[$r["day"]]++;}
}
foreach ($a as $k => $v) {
print "$k = $v<br>";
}
foreach ($a as $k => $v) {
$sum[]=array("day"=>$k, "misses" => $v);
}
print_r($sum);
返回
Array (
[0] => Array ( [day] => 2013-01-01 [misses] => 2 )
[1] => Array ( [day] => 2013-01-02 [misses] => 1 )
[2] => Array ( [day] => 2013-01-03 [misses] => 1 ) )