我有一个多维数组。我需要对数组中具有相同索引名称的值进行分组和求和。下面是我所拥有的:
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;
}
}
1条答案
按热度按时间gab6jxml1#
如果将
item_name
作为新配料数组的键,则可以轻松地检查是否已经为此配料创建了条目得到的
$ingredients
数组看起来大致相同,只是键将是项目名称,而不是数字(0、1、2等