Home > front end >  How to remove an element from array and reset the key in php
How to remove an element from array and reset the key in php

Time:09-23

I have an array like below.

Array ( 
[items] => Array ( 
  [0] => Array ( [product_id] => 16073 [product_name] => product one ) 
  [1] => Array ( [product_id] => 19137 [product_name] => product two ) 
  [2] => Array ( [product_id] => 19143 [product_name] => product three ) 
) 

)

I want to delete any of the array element, for example remove( 2nd element) this [1] => Array ( [product_id] => 19137 [product_name] => product two )

After remove this , i want my final array like below.

Array ( 
[items] => Array ( 
  [0] => Array ( [product_id] => 16073 [product_name] => ARMANI EXCHANGE Rectangular Sunglasses, AX2029S [url] => url_1) 
  [1] => Array ( [product_id] => 19143 [product_name] => OLIVER PEOPLES L.A. Rectangular Sunglasses, OV1289S  [url] => url_2) 
) 

)

I tried array_values() function, it will not give me the result. I am unable to re arrange the array format or anything, i want to achieve this with this format only. Can some one please suggest me a way to do this?

Update

$productId = $this->request->getParam('product_id');
    $customerSessionData = $this->customerModelSessionFactory->create();
    $products = $customerSessionData->getHtoProducts(); 
    foreach($products['items'] as $key  => $product){
        if($product['product_id'] == $productId){
            unset($products['items'][$key]);
            $product_name = $product['product_name'];
            
        }
    }
    array_values($products); print_r($products);
    $customerSessionData->setHtoProducts($products);

CodePudding user response:

Use unset() before array_values():

<?php

    $data = [
            [ 'product_id' => 16073, 'product_name' => 'p1' ],
            [ 'product_id' => 19137, 'product_name' => 'p2' ],
            [ 'product_id' => 19143, 'product_name' => 'p3' ]
    ];

    unset($data[1]);
    $data = array_values($data);

    var_dump($data);

Based on OP's code: Seems like you're trying to unset something from the items array, therefore you'll need to array_values in the loop:

$productId = $this->request->getParam('product_id');
$customerSessionData = $this->customerModelSessionFactory->create();
$products = $customerSessionData->getHtoProducts(); 
foreach($products['items'] as $key  => $product){
    if($product['product_id'] == $productId){
        unset($products['items'][$key]);
        $products['items'] = array_values($products['items']);
        $product_name = $product['product_name'];
        
    }
}
print_r($products);
$customerSessionData->setHtoProducts($products);

CodePudding user response:

unset($arr[1]); 
$arr = array_values($arr);
  • Related