簡體   English   中英

array_key_exists() 期望參數 2 是數組,null 給定 - Cakephp 3

[英]array_key_exists() expects parameter 2 to be array, null given - Cakephp 3

朋友們,我感謝任何意見。

我遇到了 array_key_exists 的問題。 我需要檢查購物車中是否已經存在產品。 我這樣做是這樣的:

.
$session = $this->request->getSession();
            $cart = $session->read( 'cart' );
            
            if (array_key_exists($order->product_id, (array) $cart)) {
                $this->Flash->error('Invalid request');

            } else {
                $cart[] = $order;
                $session->write('cart', $cart );
                $this->Flash->success($order->product->name_product . ' has been added to the shopping cart');
                return $this->redirect( ['action' => 'index'] );

            }
            return $this->redirect($this->referer());
        } else {
            return $this->redirect(['action' => 'index']);
        }
.
.

我收到了下面的錯誤,但現在隨着更新它不再存在。 但是 function 仍然對我沒有幫助。

array_key_exists() expects parameter 2 to be array, int given

即使產品已添加,該產品也會添加到購物車中。 我需要將所選產品 ID 與購物車中已有的產品 ID 進行比較。 訂單信息基本是:id、數量、user_id、product_id。

如果有人可以分析某種方法來檢查已安裝數組中的 id,我將不勝感激。

當你這樣做時:

$cart[] = $order;

您要求 PHP 在$cart數組的末尾添加一個新元素,為其提供下一個可用的數字鍵。 然后,您嘗試查看產品 ID 是否作為數組中的鍵存在。 除非您的產品 ID 像 0 和 1,否則這不太可能發生。 如果您希望您的購物車按產品 ID 鍵入,請使用

$cart[$order->product_id] = $order;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM