PHP Loop Question

Hey.

I’m trying to convert my session data from a simple shopping cart into Paypal friendly Javascript.

The format that I’ve got working for Paypal looks like this:

    var cartItems = [{
                name: "Product 1",
                description: "Description of product 1",
                quantity: 1,
                price: 50,
                sku: "prod1",
                currency: "USD"
            }, {
                name: "Product 2",
                description: "Description of product 2",
                quantity: 3,
                price: 20,
                sku: "prod2",
                currency: "USD"
            }, {
                name: "Product 3",
                description: "Description of product 3",
                quantity: 4,
                price: 10,
                sku: "prod3",
                currency: "USD"
            }];

So I’ve attempted this:

    var cartItems = [
              
              <?php foreach($_SESSION["cart"] as $paypalCart){
                  echo '{
              name: "'.$paypalCart['item_name'].'",
              description: "'.$paypalCart['item_name'].'",
              quantity: '.$paypalCart['item_quantity'].',
              price: '.$paypalCart['product_price'].',
              sku: "prod",
              currency: "USD"
                  },';
              }
           ?>];

This approach leaves me with a trailing comma. I’ve found various solutions for the problem but none I can successfully apply with my current abilities

Instead of echoing out directly, load it to a variable in the loop, then once outside the loop echo out the variable except for the last character.

Hey thanks Dave. Not sure if this is what you meant, but I got this to work:

Blockquote

var cartItems = [
            
            
            <?php
            $paypalArray = array();
            foreach($_SESSION["cart"] as $paypalCart){
                $paypalArray[] = '{
            name: "'.$paypalCart['item_name'].'",
            description: "'.$paypalCart['item_name'].'",
            quantity: '.$paypalCart['item_quantity'].',
            price: '.$paypalCart['product_price'].',
            sku: "prod",
            currency: "USD"
                }';
            }
            echo implode(',', $paypalArray);

            ?>];

That looks like Json.
Can’t you use json_encode()?

2 Likes