Justin
Justin

Reputation: 29

Calculate total price for each recipe in a Multi dimensional Array PHP

I'm trying to work out how to:

Upvotes: 0

Views: 275

Answers (3)

Andreas
Andreas

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);

https://3v4l.org/boMES

Upvotes: 1

Nigel Ren
Nigel Ren

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

Niels
Niels

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

Related Questions