问题描述:

I've got an interesting problem with a few different ways to solve it. I'm creating a reporting page for a small tool that takes the output from commands run on the command line and splits the aggregate info out into easier to read tables.

My code starts by running the cmd and filtering out some input. I'm running this in windows, so it's using find instead of grep.

Here is an example of a few rows I might get back from the command, each row comes back as an element in an array:

Client client1 2011/06/16 root /appl/now 'area1: info'

Client client2 2011/06/16 root /appl/now 'area2: adds'

Client client3 2011/06/16 root /appl/now 'area3: text'

Client client4 2011/06/16 root /appl/now 'area4: text'

Client client5 2011/06/16 root /appl/now 'area3: text'

Client client6 2011/06/16 root /appl/now 'area3: adds'

Client client7 2011/06/16 root /appl/now 'area1: info'

What I need to do is take each row from the above output and group them based on the area<#> entry. Each unique string there (info, adds, etc) is a table, and every entry that has that value has another cmd run, and the output stored in the table. So for the above output I would have 4 tables; area1 would have 2 entries, area2 would have 1 entry, area3 would have 3 entries, and area4 would have 1 entry.

These values are stored in a database so I can do a select statement to get them, and then compare them against my original array, or loop through the array and store each unique value in another array. The first option seems faster when I have a very large dataset, and the second option seems faster when I have a small dataset. Which way is faster? Is there a better way that I haven't thought of?

Now, to compare the array of all values against the array of unique values in order to group them into separate tables, what is the fastest way? I'm currently looping through, and if the value matches the unique value, I add that element to the table. This is done with nested foreach loops, which isn't very efficient. Any suggestions?

网友答案:

You should create an array of groups and iterate though your data set only once, as opposed to your nested loop design. It would look something like:

<?php 
foreach($dataset as $row):
    $groups[$row['area_key']][] = $row;
endforeach; 
?>

You would then create your tables from the $groups array.

相关阅读:
Top