PHP - How to organize the value of the array, reset its key and start the key with 0 index?

advertisements

I'm working on cart functionality in one of my projects. We are using Laravel 5.3 and cart item is stored in Laravel session as an array. So if I have 3 items in my cart (add_to_cart Laravel session) it looks like this:

array:3 [▼
        0 => array:6 [▼
       "sku" => "brs000500"
       "price" => "500"
       "quantity" => "1"
       "brand_id" => "1"
       "brand_name" => "Baskin Robbins"
       "brand_img" => "http://s3.giftcardsindia.in/2015/06/01/original-556c659cc05cf.jpg"
       ]
       1 => array:6 [▼
       "sku" => "fab001000"
       "price" => "1000"
       "quantity" => "1"
       "brand_id" => "6"
       "brand_name" => "Fabindia"
       "brand_img" =>"http://s3.giftcardsindia.in/2015/06/01/original-556c64882baa7.jpg"
       ]
       2 => array:6 [▼
      "sku" => "tnq010000"
      "price" => "10000"
      "quantity" => "1"
      "brand_id" => "46"
      "brand_name" => "Tanishq"
      "brand_img" => "http://s3.giftcardsindia.in/2015/06/01/original-556c47dd2ca85.jpg"
      ]
]

Now I have developed remove item from cart functionality using array key (index). So when user clicks on any item to remove it from cart I send key of that product array to controller function and using unset array function I remove whole array of particular key from session.

From above example let's assume that I have removed product of key 0 after that I got array as below:

array:1 [▼
   0 => array:2 [▼
      1 => array:6 [▼
      "sku" => "fab001000"
      "price" => "1000"
      "quantity" => "1"
      "brand_id" => "6"
      "brand_name" => "Fabindia"
      "brand_img" => "http://s3.giftcardsindia.in/2015/06/01/original-      556c64882baa7.jpg"
      ]
     2 => array:6 [▼
     "sku" => "tnq010000"
     "price" => "10000"
     "quantity" => "1"
     "brand_id" => "46"
     "brand_name" => "Tanishq"
     "brand_img" => "http://s3.giftcardsindia.in/2015/06/01/original-556c47dd2ca85.jpg"
     ]
  ]
]

When shown this structure is for sure not the same as when I stored item in cart.

So what I want is to remove first key of 0, for key 1 and 2 will be outside key 0 and result array will start with key 0.

In short, I need array structure like first example that I use here in question.

How to arrange this array structure?


array_splice do it for you :)

array_splice($cartArray, $key, 1);