【问题标题】:Update the value if same key of array or insert as new value如果数组的键相同或插入新值,则更新值
【发布时间】:2015-04-09 12:57:41
【问题描述】:

我正在使用 laravel 框架制作一个极简主义的电子商务 Web 应用程序,我是一个新手。

我想要实现的是当会话中存在产品时,我想在单击Add to Cart 按钮时更新该产品的数量。如果它在会话中不存在,我想将它插入到会话中。

到目前为止我尝试过的代码:

public function store( $id ) {

    $product = Product::findOrFail( $id );

    if ( \Session::has( 'cart' ) && is_array( \Session::get('cart') ) ) {
        \Session::push('cart', ['product' => (int)$id, 'quantity' => 1 ]);
    } else {
        \Session::put('cart', ['product' => (int)$id, 'quantity' => 1 ]);
    }

    \Session::flash('added_product', 'Product Added in the cart');

    return \Redirect::back();
}

以上代码的结果是:

array:3 [▼
  0 => array:2 [▼
    "product" => 1
    "quantity" => 1
  ]
  1 => array:2 [▼
    "product" => 2
    "quantity" => 1
  ]
  2 => array:2 [▼
    "product" => 1
    "quantity" => 1
  ]
]

想要的结果是:

array:2 [▼
  0 => array:2 [▼
    "product" => 1
    "quantity" => 2
  ]
  1 => array:2 [▼
    "product" => 2
    "quantity" => 1
  ]
]

请帮我解决这个问题。谢谢。

更新 1

在优素福回答后,我得到了以下结果:

array:4 [▼
  "product" => 1
  "quantity" => 1
  0 => array:2 [▼
    "product" => 3
    "quantity" => 1
  ]
  1 => array:2 [▼
    "product" => 2
    "quantity" => 1
  ]
]

【问题讨论】:

  • 抱歉,我刚刚注意到您要执行的操作。我会更新我的答案。
  • 好的..等待它..
  • 好的,为你添加了新答案
  • 谁能帮帮我?
  • 检查我的最新编辑,我认为它应该可以工作

标签: php arrays laravel multidimensional-array laravel-5


【解决方案1】:

我不知道 Laravel,但我认为您可以像这样处理数组:

public function store( $id ) {

    $product = Product::findOrFail( $id );

    if ( \Session::has( 'cart' ) && is_array( \Session::get('cart') ) ) {
        $cart = \Session::get('cart');
        $found = false;
        foreach($cart as $i=>$el)
        {
           if($el['product'] == $id)
           { 
             $cart[$i]['quantity']++;
             $found = true;
           }
        }
        if(!$found) {
          $cart[] = ['product' => $i, 'quantity' => 1];
        }
        \Session::put('cart', $cart);
    } else {
        \Session::put('cart', [['product' => (int)$id, 'quantity' => 1 ]]);
    }

    \Session::flash('added_product', 'Product Added in the cart');

    return \Redirect::back();
}

【讨论】:

    【解决方案2】:

    如果该条目存在于您正在创建的会话中,并将另一个项目推送到数组中,这会导致重复的结果。您可能应该将 if 块更改为以下内容:

    $value = Session::pull( 'cart', ['product' => int($id), 'quantity' => 0 ]);
    $value['quantity'] += 1;
    Session::put('cart', $value);
    

    pull 方法调用将为您获取购物车值(如果存在)或创建一个新值(如果不存在)(数量为 0)。它增加数量,这意味着如果它已经存在,它将增加 1,如果它是您在 pull 调用中创建的数量,则设置为 1。当您调用pull 时,该值将从会话中删除,因此您将通过调用put 将新值放回会话中。希望这能提供更简洁的代码。

    您可以将数组安全检查添加到增量语句中:array_key_exists('quantity')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      • 2017-09-27
      • 2018-10-20
      相关资源
      最近更新 更多