php 从数据库表分组项目和计算总价格为每个项目给定的项目数量

kognpnkq  于 2023-03-07  发布在  PHP
关注(0)|答案(1)|浏览(100)

我有一个多维数组。我需要对数组中具有相同索引名称的值进行分组和求和。下面是我所拥有的:

Array
(
[Garlic Potatoes] => 625
[Rice] => 1025
[Chicken Shawarma] => 1675
[Pita Bread Sm] => 6
[Pita Bread Large] => 14
[Beef Shawarma] => 1755
[Can of Pop] => 2
[Brioch Bun] => 2
[Chicekn Shawarama] => 135
)

我怎样才能得到一个Chicken Shawarma的示例,并且qty = 1405?我需要使用foreach吗?

$sql = "SELECT menu_id, SUM(quantity) AS qty FROM daily_consumption_details WHERE consumption_id = $id GROUP BY menu_id";
$res = $conn->query($sql);

$ingredients = [];

while($menu = $res->fetch_object())
{

    $sql_ing = "SELECT item_name, quantity FROM menu_details WHERE menu_id = $menu->menu_id ";
    $rs = $conn->query($sql_ing);
    while($items = $rs->fetch_object())
    {
        $qty = $menu->qty * $items->quantity;
    
        if ( array_key_exists(trim($items->item_name), $ingredients) ) 
            $ingredients[trim($items->item_name)] = $qty + $ingredients[trim($items->item_name)];
        else 
            $ingredients[trim($items->item_name)] = $qty; 

    }
}
gab6jxml

gab6jxml1#

如果将item_name作为新配料数组的键,则可以轻松地检查是否已经为此配料创建了条目

while($menu = $res->fetch_object())
{

    $sql_ing = "SELECT item_name, quantity FROM menu_details WHERE menu_id = $menu->menu_id ";
    $rs = $conn->query($sql_ing);
    while($items = $rs->fetch_object())
    {
        $qty = $menu->qty * $items->quantity;
        $item = trim($items->item_name);
        if ( array_key_exists($item, $ingredients) ) {
            $ingredients[$items] += $qty;
        } else {
            $ingredients[$items] = $qty; 
        }
    }
}

得到的$ingredients数组看起来大致相同,只是键将是项目名称,而不是数字(0、1、2等

相关问题