解析数据转换成HTML表格和类别

问题描述:

我导入一个文件,说june.txt,将有诸如以下数据数据:解析数据转换成HTML表格和类别

Sandy,820,384,133,18,408 
    Wanda,120,437,128,807,595 
    Jane,631,415,142,687,600 
    Andrea,179,339,349,594,986 
    Wanda,803,191,6,807,322 
    Jane,741,975,34,15,832 
    Jane,239,714,250,94,497 
    Andrea,219,188,411,584,713 

然后是PHP会解析成2种的区别方法:

第一种方式是与合计捆绑在一起的所有名称,如:

Sandy 820  384  133  18  408 
    Total 820  384  133  18  408 


    Jane 631  415  142  687  600 
    Jane 741  975  34  15  832 
    Jane 239  714  250  94  497 
    Total 1611 2104 426  796  497 


    Andrea 179  339  349  594  986 
    Andrea 219  188  411  584  713 
    Total 398  527  760  1178 1699 

    Wanda 120  437  128  807  595 
    Wanda 803  191  6  807  322 
    Total 923  628  134  1614 917 

第二种方法将总计并在大名单中添加名字连在一起,如

Sandy 820  384  133  18  408 
    Jane 1611 2104 426  796  497 
    Andrea 398  527  760  1178 1699 
    Wanda 923  628  134  1614 917 

任何逻辑或建议将是有益的,我是新来的PHP和不知道如何甚至可以做到。我的计划是最终在HTML表格中显示结果并让它们可排序,但我可以在以后解决这个问题,除非有人觉得有义务在解析中添加这些。

我认为对你有用的东西是explode函数。

至于创造这些意见我会通过加载所有这些数据转化为基于名称数组的关联数组开始,然后遍历必要的:

$datafile = file("filename.txt"); 

// reads lines into an associative array (key is the name) of arrays 
// where each sub-array is a list of the records for each name 
$arr = array(); 
foreach($datafile as $line){ 
    $temp = explode(',', $line); 
    $arr[$temp[0]][] = $temp; 
} 

// iterate over each person 
foreach($arr as $person_set){ 

    // create an array to hold the sum of each column 
    // (and the name in the first column) 
    $totals = array(); 
    $totals[0] = $person_set[0][0]; 
    for($i = 1; $i < length($record); $i++){ 
     $totals[$i] = 0; 
    } 

    // now iterate over each record for this person 
    foreach($person_set as $record){ 

     // print a particular record 
     echo implode(' ', $record) . '<br>'; 

     // add each column (1..end) to the totals array 
     for($i = 1; $i < length($record); $i++){ 
      $totals[$i] += $record[$i]; 
     } 
    } 

    // print out the totals line 
    echo implode(' ', $totals) . '<br><br>'; 
} 

我会离开这个数据格式化成一张表作为练习。

+0

这太棒了,我将数据格式化为表格。看来你实际上是这样做的,所以它总计每个列和行为1的数字为达到分组,而我想仅总计列,如在我的示例 – ParoX 2010-07-09 10:39:00

+0

我得到//添加每列(1..end) for循环并将其替换为:$ totals [i] + = $ record [1]; $ totals [i + 1] + = $ record [2]; $ totals [i + 2] + = $ record [3]; $ totals [i + 3] + = $ record [4]; $ totals [i + 4] + = $ record [5]; ...似乎做我想做的事。我不确定我(没有$)代表。 – ParoX 2010-07-09 11:58:30

+0

@布莱恩,这是一个错字,应该是$ totals [$ i]到处是$ total [i],请参阅我的编辑。 – 2010-07-09 12:34:20

好吧,首先,我会用PHP的fgetcsv()这样一个文件。 Docs

你可以尝试这样的脚本:

<?php 
echo "<table>"; 

$data = file("june.txt"); 
foreach($data as $month) { 
    $line = explode(',', $data); 
    echo '<tr><td>', implode('</td><td>', $line), '</td></tr>'; 
} 

echo "</table>"; 

编辑: 我不好,没有注意到你整理/分组/总计。尽管如此,这应该让你在正确的轨道上。关键是使用$line作为您的信息来源。只需将它编译成数组并稍后输出(而不是在循环中)。