[英]Use a nested array to create unique keys, and count values
In PHP I want to construct an array that uses the distinct $raw['day']
as each row, and count up all the $raw['delay']
that are greater than 0: 在PHP中,我想构造一个使用不同的$raw['day']
作为每一行的数组,并计算大于0的所有$raw['delay']
:
Start 开始
$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),
);
Result 结果
array(
[0] => ("day" => "2013-01-01", "misses" => 2),
[1] => ("day" => "2013-01-02", "misses" => 1),
[2] => ("day" => "2013-01-02", "misses" => 1),
)
What I've tried: 我尝试过的
I was thinking first I'd get all unique days: 我首先想到的是我会得到所有独特的日子:
$all_days = array_column($raw, 'day');
$unique_days = array_unique($all_days);
Now that I've got all unique days, I can loop through $raw
again and increment the misses. 现在我已经拥有了所有独特的日子,我可以再次遍历$raw
并增加未命中率。 But this seems overly verbose, and I figured among PHP's array functions there would be an easier solution. 但这似乎太冗长了,我发现在PHP的数组函数中会有一个更简单的解决方案。
foreach ($raw as $row) {
if ($row['delay'] > 0) {
$unique_days[$row['day']]++
}
}
you can use array_walk function, but I suppose the only thing you need is: 您可以使用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']]++
}
}
it will store only unique days with proper counter 它将仅存储具有适当计数器的唯一日期
UPDATE check places 1 and 2 - first one is needed if you need all days in final array, second is needed if you need only unique days and don't want warning UPDATE检查位置1和2-如果需要在最终数组中放置整天,则需要第一个;如果仅需要唯一的天并且不希望警告,则需要第二个
This is one possible approach: 这是一种可能的方法:
$sum=array();
foreach ($raw as $r) {
if ($r["delay"]>0) $sum[$r["day"]]++;
}
and then 接着
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);
Returns 返回
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 ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.