-2

Sorry for the beginner question I'm still learning PHP.

I have a foreach statement which grabs some product data from an API which works as expected. I'm now trying to add in an additional foreach statement to grab the cart totals but when I add this in my text editor is throwing up a syntax error. No doubt I'm doing something wrong could anyone point me in the right direction please?

Here's is the segment of code where I'm trying to add in the foreach totals. far.

     if (!empty($data['data'])) {

        // Set vars
        $products = array();
        $output = '';

        // Cart Values
        $cartValues = $data['data'];
        $output .= $modx->getChunk($cartTpl, $cartValues);

        // Product Values
        foreach($data['data']['products'] as $item) {
         foreach($item as $key => $value) {
            $products[$key] = $value;
        }

        $listProducts .= $modx->getChunk($productsTpl, $products);
        $output = str_replace('[[+products]]', $listProducts, $output);

        // Total Values
        foreach($data['data']['totals'] as $total) {
         foreach($total as $key => $value) {
            $totals[$key] = $value;
        }

        $listTotals .= $modx->getChunk($totalsTpl, $totals);
        $output = str_replace('[[+totals]]', $listTotals, $output);

    }
alienbuild
  • 133
  • 10
  • You could paste error output here. – Luka Aug 25 '18 at 19:01
  • Be careful with foreachs as the more you have in your code, the slower and the more unreadable the entire code will be. Most of the time a simple PHP array function may be the right solution instead of doing your own stuff with like 4 foreachs and 2 of them are in another one. – TheKeymaster Aug 25 '18 at 21:20

3 Answers3

0

Add a $sum = 0; before the loop And put $sum += $value;

Dice
  • 237
  • 1
  • 8
0

You're missing the closing curly brace for your foreach:

    // Product Values
    foreach($data['data']['products'] as $item) {
     foreach($item as $key => $value) {
        $products[$key] = $value;
     } // <--- Missing closing curly brace
    }

    // (...)

    // Total Values
    foreach($data['data']['totals'] as $total) {
     foreach($total as $key => $value) {
        $totals[$key] = $value;
     } // <--- Missing closing curly brace
    }
0

You have missed closing curly braces after for loop at line 17 and 26 your snippet:

https://codebrace.com/editor/b03a5b34c