逗号分开的foreach

时间:2013-03-06 01:02:03

标签: php foreach

这个想法是以逗号分隔的产品列表,但该列表必须包含" product_name(pipe)product_price * quantity" 例如,如果订单包含2xABC($ 10.00)和3xDEF($ 20.00),我的输出需要是" ABC|20.00,DEF|60.00" 我有以下代码:

    $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();
      }

然后,我像这样运行一个foreach:

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

并想输出结果:

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

但是,像往常一样,我错过了一些东西,但这并不起作用。 :)非常感谢任何帮助。

编辑:我的错误日志中出现以下错误,没有回音:PHP Warning: implode() [<a href='function.implode'>function.implode</a>]: Argument must be an array in line XXX(指echo $listFinal;

1 个答案:

答案 0 :(得分:2)

你只是连接一个字符串,试试这个:

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

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