【问题标题】:Need to Add two varibles under same value in array需要在数组中添加两个相同值的变量
【发布时间】:2015-05-25 01:49:11
【问题描述】:

我有一个购物车系统,它使用array_push 将购物车物品添加到购物车。问题是它不会将项目的价格添加到数组中。我怎样才能添加它:

Item - ItemPrice
Item_2 - ItemPrice_2
Item_3 - ItemPrice_3

作为一组。不作为单独的项目

Item
ItemPrice
Item_2
ItemPrice_2
Item_3
ItemPrice_3

我添加它的代码是这样的:

array_push($_SESSION['cart'],'Item_2');

有没有办法为这个 Item_2 添加价格




编辑:或者我应该这样做

itemName -> item_1, item_2, item_3              itemPrice -> itemPrice_1, itemPrice_2, itemPrice_3

但我不知道如何正确编码。 我还在“我的购物车”页面的表格中要求这样做:

$array = $_SESSION['cart'];
echo "<table class=cart>";     
foreach( $array as $key => $value ){
    echo "<tr><td><p>" . $key . "</p></td><td><p>" . $value . "</p></td><td><p><a href=#>Remove?</a></p></td></tr>";
}
echo "</table>";

【问题讨论】:

  • 为什么不将数组推送到购物车上? array_push($_SESSION['cart'],array('Item_2' =&gt; 'price')); 之类的?
  • @andrewsi 我这样做了,现在它给了我和错误“解析错误:语法错误,第 15 行 C:\xxxxxxxx 中的意外 '=>' (T_DOUBLE_ARROW)”
  • 第 15 行是 "array_push($_SESSION['cart'],'itemName' => '13.99'); // "
  • 您也需要将其包装在array() 中。
  • @andrewsi 谢谢,但其他人的解决方案效果更好。但无论如何感谢上帝保佑你。

标签: php arrays session add


【解决方案1】:

您可以将价格指定为值,将名称指定为数组的键,因此:

$_SESSION['cart'][item] = item_price;

【讨论】:

    【解决方案2】:

    怎么样:

    $_SESSION['cart'][] = array('item' => 'itemName', 'price' => 'itemPrice');
    
    foreach ($_SESSION['cart'] as $array) {
        echo "<tr><td>" . $array['item'] . "</td><td>" . $array['price] . "</td><td><a href="#">Remove?</a></td></tr>";
    }
    

    【讨论】:

    • 我试过了,但没有奏效,卢克的解决方案效果更好。不管怎么说,还是要谢谢你。上帝保佑你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 2021-01-28
    • 1970-01-01
    • 2018-05-17
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多