如何对表PHP上的每一列求和

时间:2013-05-07 01:57:57

标签: php html-table sum

我想对此表中的每一列求和:

$docid = array(1, 2, 3, 4, 5);
        $table = array('technology' => 1 , 'languange' => 2, 'town' => 3, 'gadget' => 4, 'smartphone' => 5);
        echo "<table><tr><th>Token/Document</th>";
        $count = count($table);
        $doc_count = count($docid);
        for($i=1; $i<=$count; $i++)
        {
            echo "<th>Doc.$i</th>";
        }
        foreach($table as $key=>$value)
        {
            echo "<tr><td>$key</td>";
            for($i=0; $i<$doc_count;$i++)
            {
                $random = rand(1, 8);
                echo "<td>$random</td>";
            }
        }
        echo "</tr><td>RESULT</td>";
        for($i=0; $i<$doc_count;$i++)
        {
            echo "<td>...(what should i use?)...</td>";
        }
        echo "</tr></table>";

示例:

  

=============================================

     

|令牌/文件| Doc.1 | Doc.2 | Doc.3 | Doc.4 | Doc.5 |

     

=============================================

     

|技术........... | .... 5 ..... | .... 7 ..... | .... 4 ..... | .... 2 ..... | .... 1 ..... |

     

|语言............. | .... 6 ..... | .... 8 ..... | .... 1 ..... | .. ..5 ..... | .... 5 ..... |

     

|镇.................... | .... 5 ..... | .... 3 ..... | .... 2。 .... | .... 7 ..... | .... 6 ..... |

     

|小工具................. | .... 4 ..... | .... 1 ..... | .... 2 .... 。| .... 4 ..... | .... 8 ..... |

     

|智能手机......... | .... 3 ..... | .... 7 ..... | .... 3 ..... | .... 1。 .... | .... 2 ..... |

     

=============================================

     

RESULT ............... | .... .... 23 | .... .... 26 | .... 12 .... | .... 19 .... | 22 .... |

如何对每一列进行求和?

2 个答案:

答案 0 :(得分:1)

你可以做这样的事情

$sum = 0;
for($i=0; $i<count($your_array); $i++)
{
    //your codes
    $sum += $values; //values to be summed up
}

echo "Total = ". $sum;

我希望这会有所帮助。

答案 1 :(得分:1)

您需要存储每个$random,以便在最后一行中将它们合计。

$random = rand(1, 8);
$results[$i][] = $random;  // store $random value in array

然后使用array_sum()

对数组进行总计
echo "<td>".array_sum($results[$i])."</td>";

    $docid = array(1, 2, 3, 4, 5);
    $table = array('technology' => 1 , 'languange' => 2, 'town' => 3, 'gadget' => 4, 'smartphone' => 5);
    echo "<table><tr><th>Token/Document</th>";
    $count = count($table);
    $doc_count = count($docid);
    for($i=1; $i<=$count; $i++)
    {
        echo "<th>Doc.$i</th>";
    }
    foreach($table as $key=>$value)
    {
        echo "<tr><td>$key</td>";
        for($i=0; $i<$doc_count;$i++)
        {
            $random = rand(1, 8);
            $results[$i][] = $random; // save in array for totaling
            echo "<td>$random</td>";
        }
    }
    echo "</tr><td>RESULT</td>";
    for($i=0; $i<$doc_count;$i++)
    {
        echo "<td>".array_sum($results[$i])."</td>"; // total array using array_sum()
    }
    echo "</tr></table>";

phpfiddle - http://phpfiddle.org/main/code/psy-ejm