$data = array(
array('title' => 'apple', 'quantity' => 5, 'price' => 1.2),
array('title' => 'orange', 'quantity' => 3, 'price' => 0.8),
array('title' => 'banana', 'quantity' => 2, 'price' => 1.5),
array('title' => 'apple', 'quantity' => 2, 'price' => 1.1),
array('title' => 'banana', 'quantity' => 1, 'price' => 1.3),
array('title' => 'orange', 'quantity' => 4, 'price' => 0.9),
);
$sums = array();
foreach ($data as $row) {
$title = $row['title'];
if (!isset($sums[$title])) {
$sums[$title] = array('quantity' => 0, 'price' => 0);
}
$sums[$title]['quantity'] += $row['quantity'];
$sums[$title]['price'] += $row['quantity'] * $row['price'];
}
foreach ($sums as $title => $sum) {
echo $title . ' ';
echo 'quantity: ' . $sum['quantity'] . ' ';
echo 'price: ' . round($sum['price'], 2) . '
';
}
输出结果:
apple quantity: 7 price: 9.18
orange quantity: 7 price: 4.9
banana quantity: 3 price: 4.1
上一篇:按标题中的字符数排序列表
下一篇:按标题字符串自定义排序节