简体   繁体   中英

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

I need to loop through a set of data (example below) and generate an aggregate. Original data format is CSV (but could be other kind).

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

I need to group the quantities by LOGON and QUERY, so at the end I would have an array like:

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

I usually use a code like this:

$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;

Sincerely, I don't think this is nice, as I have to repeat last statement to include last line. So, is there a more elegant way of solving this in PHP?

Thanks!

You simply would need to check for the existence of a key, then increment - create missing keys at any time with value 0.

Then you dont need to repeat anything at any time:

$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']; 
}

For readability and to avoid misstakes, you should generate the key just one time, instead of performing the same concatenation over and over:

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']; 
}

this would allow you to refactor the key without touching several lines of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM