Rooncicle
Rooncicle

Reputation: 106

Tallying instances of unique values in an HTML table

I'm looking to count the instances of each unique value in an HTML table and return the results in a table of it's own. The table is generated from a user's text input. So for example the users input might look like this:

Report 46     Bob Marley   4/20/2013    Summary: I shot the sheriff    Case #32  User Error
Report 50    Billy The Kid    7/14/2013   Summary: I'm just a boy in a grown up world   Case #33    User Experience
Report 51    Oscar The Grouch    10/10/2013   Summary: Refuse, reuse, recycle   Case #33    User Experience

where the large spaces are tabs.

Which would return:

<table>
 <tr>
  <td>Bob Marley</td><td>46</td><td>4/20/2013</td><td>Case #32</td><td>User Error</td>
 </tr>
 <tr>
  <td>Billy The Kid</td><td>50</td><td>4/20/2013</td><td>Case #33</td><td>User Experience</td>
 </tr>
 <tr>
  <td>Oscar The Grouch</td><td>51</td><td>10/10/2013</td><td>Case #33</td><td>User Experience</td>
 </tr>
</table>

What I need to do is 1) tally the number of reports, 2) tally the number of times each case number appears, 2) and tally the number of times each category appears and then display it on the next page like such:

Number of reports: 
3

Cases:
Case #33 - 2
Case #32 - 1

Categories:
User Experience - 2
User Error - 1

I'm looking for any suggestions on how I might approach this problem. I'm using and learning Javascript/HTML (and jQuery), but would be open to using PHP, SQL, etc. if those tools are more appropriate.

I was thinking of passing the table values to an array and then utilizing a for loop and regexes to count unique values, but I'm not sure if that's the best approach.

EDIT

One more detail that I didn't explicitly state is that I have access to the user input data (i.e. tab-separated text) prior to it being turned into a table. So, if it would be easier to tally the values in question prior to converting it into a table, then please let me know.

Upvotes: 0

Views: 288

Answers (1)

Chrysus
Chrysus

Reputation: 359

As far as PHP, you can store the table HTML into a string and load it into a DOM parser.

http://simplehtmldom.sourceforge.net/

This is what we use for most of our projects involving page scraping, though it would work just as well for parsing your HTML from a string using their function:

$html = str_get_html($yourHtmlString);

Then you can loop through each tr, and from there you can look into each td to add to your tallies.

i.e. to get the category of the third row, you would use:

$html->find("table", 0)->find("tr", 2)->find("td", 4)->plaintext;

You can loop through the table like:

$reportCount = 0;
$reportCases = array();
foreach ($html->find("table", 0)->find("tr") as $tableRow) {
    $reportCount++; 
    $reportCases[] = $tableRow->find("td", 1)->plaintext;
}

etc. though of course also storing all your other necessary data, then formatting it into your table output as needed.

Upvotes: 2

Related Questions