eibersji
eibersji

Reputation: 1216

Laravel: Sum of foreach

I have this foreach loop:

my $items looks like this:

array:2 [▼
  0 => array:3 [▼
    "variant_id" => "393c6c70-8cb7-11e8-815a-f9c70a1fbe8e"
    "name" => "Medicine 1"
    "quantity" => "1"
  ]
  1 => array:3 [▼
    "variant_id" => "8a80d340-e0c1-11e8-86a4-3b06d2b50e37"
    "name" => "Medicine 2"
    "quantity" => "1"
  ]
]

Now, in my foreach, I compare the variant_id to my database and get the points from that database and multiply it by the quantity of the Medicines.

points for Medicine 1 is = 50

points for Medicine 2 is = 20

so it should be 50(medicine 1 points) multiplied by 1 (quantity of medicine 1) and 20 x 1 (medicine 2) and then the sum of both which should be equal to 70. But when I dd($sum) what I get is 50 which is only for medicine 1.

    $sum = 0;
    foreach ($items as $variants) {
        $id = $variants['variant_id'];
        $quantity = $variants['quantity'];
        $find = Activity::where('variant_id', $id)->first();
        $act_points = $find->points * $quantity;
        $sum += $act_points;
        dd($sum);
    }

What am I missing here?

Upvotes: 0

Views: 3172

Answers (3)

Tpojka
Tpojka

Reputation: 7111

To rationalize and avoid multiple DB calls yu can do the next

$input = [
    [
        "variant_id" => "393c6c70-8cb7-11e8-815a-f9c70a1fbe8e",
        "name" => "Medicine 1",
        "quantity" => "1",
    ],
    [
        "variant_id" => "8a80d340-e0c1-11e8-86a4-3b06d2b50e37",
        "name" => "Medicine 2",
        "quantity" => "1",
    ],
];

$sum = Activity::whereIn('variant_id', array_column($input, 'variant_id'))->get()->sum(function ($s) use ($input) {
    foreach ($input as $k => $v) {
        if ($s->variant_id == $v['variant_id']) {
            return $s->points * $v['quantity'];
        }
    }
});

This will work if in $input array there is no repeating elements by variant_id. In other words if each $input[n]['variant_id'] value is unique.

Upvotes: 0

MD. Jubair Mizan
MD. Jubair Mizan

Reputation: 1560

You can see dd() as a Dump and Die. This will dump the asked data and kills the script. Because this is executed, the script gets terminated before it can finish the loop

You need to use the dd() after the foreach-loop

$sum = 0;
foreach ($items as $variants) {
    $id = $variants['variant_id'];
    $quantity = $variants['quantity'];
    $find = Activity::where('variant_id', $id)->first();
    $act_points = $find->points * $quantity;
    $sum += $act_points;
}
dd($sum);

If you do not want to halt the execution of your script, use the dump function instead.

https://laravel.com/docs/5.7/helpers#method-dd

Upvotes: 7

nottherealironman
nottherealironman

Reputation: 389

I figure out you are doing Debug dump (dd) inside foreach loop so it will just stop after the first iteration.

You should do dd outside of foreach loop.

Upvotes: 1

Related Questions