有没有办法通过php从html表格中获取产品的平均价格,并将结果作为最后一行添加到该表格中?

问题描述 投票:-1回答:1
<!DOCTYPE html>
<html>
<head>
    <meta sharset="UTF-8"/>
    <title>Project 1</title>
<style>
table
{
border-style:solid;
border-width:1px;
border-color:blue;
}
</style>
</head>
<body>

    <?php
        $smartphones = array ( 'Huawei Y7 2019' => 149,
                                'Samsung Galaxy A10' => 169,
                                'Xiaomi Redmi Note 8T' => 199,
                                 'Apple iPhone 7' => 398,
                                 'Samsung Galaxy Note9' => 550);
        printsmartphones($smartphones);
        function printSmartphones ($table)
        {
            echo "<table border='2'>
            <tr>
            <th>Smartphones</th>
            <th>Price(€)</th>";
            foreach($table as $key => $value)
            {
                echo "<tr><td>$key</td><td style=\"text-align:right; color:black\">$value</td></tr>\n";
            }

            echo "</table>";
        }
    ?>

</body>
</html>

在这个项目中,我必须以某种方式打印一个表格。该表将在左栏显示智能手机的名称,右栏显示其价格。在最后一行,它将计算并打印所有智能手机的平均价格。这就是我的代码堆叠的地方,任何知道它是如何做的吗?我自己学习php,我不能找到任何地方,我想使用array_push(),但我不知道在哪里或如何。

php html arrays average
1个回答
0
投票

Average是所有值的总和除以它的计数。所以有了这个,你就可以在foreach循环之后再增加一行。

$average = array_sum($smartphones) / count($smartphones);
echo "<tr><td>Average</td><td>{$average}</td></tr>", PHP_EOL;
© www.soinside.com 2019 - 2024. All rights reserved.