在 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'];
}
这将允许您在不接触几行代码的情况下重构密钥。
我需要遍历一组数据(下面的示例)并生成一个聚合。原始数据格式为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'];
}
这将允许您在不接触几行代码的情况下重构密钥。