0

我正在这个电子商务网站上工作,我正在尝试创建一个 JSON 数组,其中包含 PHP 中的购物车项目。

到目前为止,我有:

for ($i=0; $i < count($_SESSION['cart']); $i++) {
  $prodid = $_SESSION['cart'][$i][0];
  $sizeId = $_SESSION['cart'][$i][1];
  $colorId = $_SESSION['cart'][$i][2];
  $qty = $_SESSION['cart'][$i][3];
  $inslagning = $_SESSION['cart'][$i][4];
  $wrapCost += ($inslagning == 'YES' ? 20 : 0);
  $row = get_product_buy($prodid, $sizeId, $colorId);
  $prodname = $row['prodname'];
  $color = $row['color'];
  $size = $row['size'];
  $prodCatid  = $row['catid'];
  $image = $row['biggerimage'];
  $box = $row['box_number'];

  for ($j=0;$j<$qty;$j++) {
    $cart = array(
        'reference' => '123456789',
        'name' => $prodname,
        'quantity' => $qty,
        'unit_price' => $price,
        'discount_rate' => 0,
        'tax_rate' => 2500
    );
  }
}

我知道我在循环中有 $cart var,这可能是错误的。最终结果应该是这样的:

$cart = array(
    array(
        'reference' => '123456789',
        'name' => 'Klarna t-shirt',
        'quantity' => 1,
        'unit_price' => $att_betala * 100,
        'discount_rate' => 0,
        'tax_rate' => 2500
    ),
    array(
        'reference' => '123456789',
        'name' => 'Klarna t-shirt',
        'quantity' => 1,
        'unit_price' => $att_betala * 100,
        'discount_rate' => 0,
        'tax_rate' => 2500
    )
);

感谢所有帮助!

4

4 回答 4

4
于 2013-03-22T08:50:06.460 回答
0

像这样使用

$cart[] = array(
    'reference' => '123456789',
    'name' => $prodname,
    'quantity' => $qty,
    'unit_price' => $price,
    'discount_rate' => 0,
    'tax_rate' => 2500
);
于 2013-03-22T08:47:39.863 回答
0

Try Using

for ($j=0;$j<$qty;$j++) {
$cart[] = array(
    'reference' => '123456789',
    'name' => $prodname,
    'quantity' => $qty,
    'unit_price' => $price,
    'discount_rate' => 0,
    'tax_rate' => 2500
);
}

$json_enc  = json_encode($cart);
于 2013-03-22T08:51:28.567 回答
0

You are not appending to the $cart variable, you are overwriting it on every pass of the loop.

Use the [] syntax to append to an array:

$cart[]=...

Also, its good to declare an empty array at the top of the code:

$cart=array();
于 2013-03-22T08:52:19.010 回答