数据库字段中存储的数据数量乘以不同单价的和的算法,适用于记账本程序的计件数据记录,和商品记录等场景。
代码示例如下:
<?php //模拟数据库结果集 $arr = array( array( "id" => 1, "name" => "孙悟空", "nums" => 234, "unitPrice" =>1.2), array( "id" => 2, "name" => "孙悟空", "nums" => 568, "unitPrice" =>1.3), array( "id" => 3, "name" => "孙悟空", "nums" => 986, "unitPrice" =>1.8), array( "id" => 4, "name" => "孙悟空", "nums" => 423, "unitPrice" =>1.1), array( "id" => 5, "name" => "孙悟空", "nums" => 189, "unitPrice" =>1.0) ); $val = []; foreach( $arr as $value ) { $val[] = $value["nums"] * $value["unitPrice"]; } $total = array_sum( $val ); echo '总共' . $arr[0]["name"] . '先生/女士的工资是:' . $total . '元';
代码执行后的效果如下: