在 PHP 中循环数组和聚合结果的更优雅的方式


More elegant way of looping through array and aggregating result in PHP

我需要遍历一组数据(下面的示例)并生成一个聚合。原始数据格式为 CSV(但可以是其他类型)。

LOGON;QUERY;COUNT
L1;Q1;1
L1;Q1;2
L1;Q2;3
L2;Q2;1

我需要按 LOGON 和 QUERY 对数量进行分组,所以最后我会有一个这样的数组:

"L1-Q1" => 3,
"L1-Q2" => 3,
"L2-Q1" => 1,

我通常使用这样的代码:

$logon = NULL;
$query = NULL;
$count = 0;
$result = array();
// just imagine I get each line as a named array
foreach ($csvline as $line) { 
    if ($logon != $line['logon'] || $query != $line['query']) {
         if ($logon !== NULL) {
              $result[$logon . $query] = $count;
         }
         $logon = $line['logon'];
         $query = $line['query'];
         $count = 0;
    }
    $count += $line['count'];
}
$result[$logon . $query] = $count;

真诚地说,我认为这不好,因为我必须重复最后一句话以包括最后一行。那么,在PHP中是否有更优雅的方法来解决这个问题呢?

谢谢!

您只需要检查是否存在键,然后递增 - 随时创建值为 0 的缺失键。

然后,您无需随时重复任何内容:

$result = array();
foreach ($csvline as $line) { 
    if (!isset($result[$line['logon'] . $line['query']])){
       //create entry
       $result[$line['logon'] . $line['query']] = 0; 
    }
    //increment, no matter what we encounter
    $result[$line['logon'] . $line['query']] += $line['count']; 
}

为了提高可读性并避免误读,您应该只生成一次密钥,而不是一遍又一遍地执行相同的串联:

foreach ($csvline as $line) { 
   $curKey = $line['logon'] . $line['query'];
   if (!isset($result[$curKey])){
       //create entry
       $result[$curKey] = 0; 
    }
    //increment, no matter what we encounter
    $result[$curKey] += $line['count']; 
}

这将允许您在不接触几行代码的情况下重构密钥。