user1078494
user1078494

Reputation: 509

comma separated foreach

The idea is to get a comma separated list of products, but that list must contain "product_name (pipe) product_price*quantity" For example, if the order contained 2xABC (at $10.00) and 3xDEF (at $20.00), my output would need to be "ABC|20.00,DEF|60.00" I have the following code:

    $products = $db->Execute($products_query);
    while (!$products->EOF) {
        $purchasedArray[] = array('products_name'=>$products->fields['products_name'],
                                    'final_price'=>$products->fields['final_price'],
                                    'products_quantity'=>$products->fields['products_quantity']);
        $products->MoveNext();
      }

Then, I run a foreach like this:

foreach ($purchasedArray as $purchased) {
    $list .= $purchased['products_name'] . '|' . ($purchased['final_price']*$purchased['products_quantity']);
}

and want to output the result:

$listFinal = implode(','. $list);
echo $listFinal; 

But, as usual, I'm missing something and this doesn't work. :) Any help would be much appreciated.

EDIT: I get the following error in my error logs and nothing echoes: PHP Warning: implode() [<a href='function.implode'>function.implode</a>]: Argument must be an array in line XXX (referring to echo $listFinal; )

Upvotes: 0

Views: 3497

Answers (1)

Mike Purcell
Mike Purcell

Reputation: 19979

You are simply concatenating a string, try this:

foreach ($purchasedArray as $purchased) {
    $formattedProducts[] = $purchased['products_name'] . '|' . ($purchased['final_price']*$purchased['products_quantity']);
}

$listFinal = implode(',', $formattedProducts);
echo $listFinal; 

Upvotes: 2

Related Questions