Reputation: 29
I'm trying to work out how to:
Display the total cost of all recipes.
The problem is I can't get the total for each recipe (Super Energy Mix & Super Fruit Punch), my solution does not work properly to get the totals. Do I need another loop?
$recipes = array(
'Super Energy Mix' => array(
'Sugar' => array('quantity' =>'1', 'price' => '1.15'),
'Chocolate' => array('quantity' =>'1', 'price' => '2.10'),
'Squash' => array('quantity' =>'1', 'price' => '1.35'),
'Coffee' => array('quantity' =>'1', 'price' => '3.54')
),
'Super Fruit Punch' => array(
'Rum' => array('quantity' =>'1', 'price' => '3.52'),
'Vodka' => array('quantity' =>'1', 'price' => '3.53'),
'Orange Juice' => array('quantity' =>'1', 'price' => '1.35'),
'Lime' => array('quantity' =>'1', 'price' => '1.35')
)
);
$sum = '0';
foreach($recipes as $recipe => $key)
{
echo $recipe."<br/>";
foreach($key as $keys => $value)
{
echo $keys;
echo $value['price']."<br/>";
$sum += $value['price'];
}
echo $sum."<br/>";
}
Upvotes: 0
Views: 275
Reputation: 23958
You can also build new items in your array inside the foreach.
That way you can easily get subtotals and totals of each recipe.
Foreach($recipes as &$recipe){
Foreach($recipes as &$val){
$val['subtotal'] = $val['quantity'] * $val['price'];
}
$recipe['total'] = array_sum(array_column($recipe, 'subtotal'));
}
$recipes['total'] =array_sum(array_column($recipes, 'total'));
Var_dump($recipes);
Upvotes: 1
Reputation: 57121
As mentioned in the comment, you are only resetting the sum at the start, so the total is for everything so far.
Move the setting of $sum
into the loop so it gets reset for each recipe.
This version also multiplies the price by the quantity - not sure if you need this, but may be important at some point, but remove it if you don't need it.
$totalCost = 0;
foreach($recipes as $recipe => $key)
{
echo $recipe."<br/>";
$sum = 0;
foreach($key as $keys => $value)
{
echo $keys;
echo $value['price']."<br/>";
$sum += ($value['price']*$value['quantity']);
}
echo $sum."<br/>";
$totalCost += $sum;
}
echo "Total cost=".$totalCost."<br/>";
Added in total cost as per comment in question.
Upvotes: 1
Reputation: 1006
Unsetting the $sum
variable will correct your problem. I also removed $sum = '0';
since it's not necessary to tell PHP a variable is zero. I also made minor adjustments to your code to make the text on the page a little easier to read.
foreach($recipes as $recipe => $key)
{
echo '<strong>' . $recipe . "</strong><br/>";
foreach($key as $keys => $value)
{
echo $keys . ': ';
echo $value['price']."<br/>";
$sum += $value['price'];
}
echo $sum."<br/>";
unset($sum);
}
Upvotes: 1