我想在多维数组中乘以数量值,并根据数量得到结果
这是数组:
$meal_plan[$res['week']][$res2['day']][$res3['meal_plan_type']][$res3['quantity']][]=$res4;
这是循环:
foreach ($meal_plan as $week => $dayArr) {
foreach ($dayArr as $day => $meatTypeArr) {
$tFat = $tCal = $tKJoules = $tCarb = $tProt =0;
foreach ($meatTypeArr as $mealType => $meals) {
foreach ($meals as $mealQuantity => $mealq) { //quantity loop
foreach ($mealq as $meal_id => $meal) {
$tFat += $meal['total_fat'];
$tCal += $meal['calories'] ;
$tKJoules += $meal['kilojoules'] ;
$tCarb += $meal['carbs'] ;
$tProt += $meal['protien'] ;
}
}
}
}
这是我的数组,我想将cabs / protein / fat等的值乘以数量数组。怎么做 ?
Array
(
[1] => Array
(
[1] => Array
(
[Breakfast] => Array
(
[3] => Array
(
[0] => Array
(
[recepy_id] => 451
[recepy_name] => Egg Omelette
[meal_id] => 1
[total_fat] => 17.7
[calories] => 315
[kilojoules] => 1310
[carbs] => 18.6
[protien] => 18
)
)
)
[Lunch] => Array
(
[2] => Array
(
[0] => Array
(
[recepy_id] => 1016
[recepy_name] => Reduced Fat Milk
[meal_id] => 4
[total_fat] => 3
[calories] => 127
[kilojoules] => 530
[carbs] => 15.25
[protien] => 10
)
)
[1] => Array
(
[0] => Array
(
[recepy_id] => 639
[recepy_name] => Custard - Egg
[meal_id] => 4
[total_fat] => 5.2
[calories] => 82
[kilojoules] => 344
[carbs] => 1.7
[protien] => 6
)
)
[4] => Array
(
[0] => Array
(
[recepy_id] => 1026
[recepy_name] => Beef Waldorf Salad
[meal_id] => 2
[total_fat] => 11
[calories] => 288
[kilojoules] => 1202
[carbs] => 28
[protien] => 19
)
)
)
[Snack] => Array
(
[1] => Array
(
[0] => Array
(
[recepy_id] => 997
[recepy_name] => Avocado - 60g
[meal_id] => 4
[total_fat] => 13
[calories] => 125
[kilojoules] => 522
[carbs] => 0.3
[protien] => 1
)
)
)
)
)
)
答案 0 :(得分:0)
从您的代码中,您似乎每天需要单独的总计。那么你会这样做:
foreach ($meal_plan as $week => $dayArr) {
foreach ($dayArr as $day => $meatTypeArr) {
$tFat = $tCal = $tKJoules = $tCarb = $tProt = 0;
foreach ($meatTypeArr as $mealType => $meals) {
foreach ($meals as $mealQuantity => $mealq) { //quantity loop
foreach ($mealq as $meal_id => $meal) {
// Multiply each with $mealQuantity:
$tFat += $mealQuantity * $meal['total_fat'];
$tCal += $mealQuantity * $meal['calories'] ;
$tKJoules += $mealQuantity * $meal['kilojoules'] ;
$tCarb += $mealQuantity * $meal['carbs'] ;
$tProt += $mealQuantity * $meal['protien'] ;
}
}
}
// Add to result array (a set of totals per day)
$result[$week][$day] = [
"total_fat" => $tFat,
"calories" => $tCal,
"kilojoules" => $tKJoules,
"carbs" => $tCarb,
"protein" => $tProt
];
}
}
在eval.in上看到它。