0

我不知道如何通过电子邮件发送整个购物车阵列。我尝试使用 print_r 函数,但结果中只得到一项。

任何帮助将不胜感激。

<?php session_start(); ?>

<?php

if (!isset($_SESSION['cart']) || (count($_SESSION['cart']) == 0)) {
    echo '<p>Your shopping cart is empty, so <a href="L14O1_buy.php">get shopping</a>.</p>';
} else {
    echo '<table>
    <tr>
    <th>Product</th>
    <th>Cost</th>
    <th>Units</th>
    <th>Subtotal</th>
    </tr>';
    $total = 0;

    foreach($_SESSION['cart'] as $item) {

    echo "<tr>
        <td>{$item['item']}</td>
        <td>\${$item['unitprice']}</td>
        <td>{$item['quantity']}</td>
        <td>$".($item['unitprice'] * $item['quantity'])."</td>
        </tr>";
        $total += ($item['unitprice'] * $item['quantity']);
    }
    echo '</table>';
    echo "<p>Grand total: \$$total</p>";
}
?>


<?php
$to      = 'blah@gmail.zzz';
$subject = 'the subject';
$body = print_r($item);
$headers = 'From: blah@gmail.zzz' . "\r\n" .
        'Reply-To: blah@gmail.zzz' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $body, $headers);
?>
4

2 回答 2

2

仅显示最后一项,因为您的foreach ( $_SESSION['cart'] as $item ) ...循环使用该$item变量。$item 在每个循环中重新分配。在循环结束时,最后一个值仍然存在。

试试$body = print_r($_SESSION['cart'], true);吧。

于 2013-06-07T19:33:37.433 回答
0

尝试这个:

<?php

session_start(); 

$body = '';

if (!isset($_SESSION['cart']) || (count($_SESSION['cart']) == 0)) {
    echo '<p>Your shopping cart is empty, so <a href="L14O1_buy.php">get shopping</a>.</p>';
} else {
    echo '<table>
    <tr>
    <th>Product</th>
    <th>Cost</th>
    <th>Units</th>
    <th>Subtotal</th>
    </tr>';
    $total = 0;

    foreach($_SESSION['cart'] as $item) {

    echo "<tr>
        <td>{$item['item']}</td>
        <td>\${$item['unitprice']}</td>
        <td>{$item['quantity']}</td>
        <td>$".($item['unitprice'] * $item['quantity'])."</td>
        </tr>";
        $total += ($item['unitprice'] * $item['quantity']);
        $body .= print_r($item, true)."\n";
    }
    echo '</table>';
    echo "<p>Grand total: \$$total</p>";
}

$to      = 'blah@gmail.zzz';
$subject = 'the subject';
$body = "<pre>{$body}</pre>";
$headers = 'From: blah@gmail.zzz' . "\r\n" .
        'Reply-To: blah@gmail.zzz' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $body, $headers);
于 2013-06-07T19:34:44.160 回答