0

Hi all,

I'm trying to delete elements from an array - The array should be a shopping cart - So I need to ad/remove items from it.

So far I can add items no problem, but i seem to keep failing to delete the correct indexes.

The array contains a product id and the quantity of that product in the cart.

I have this:

// Cart array:
// Should that be build in another way?
$cart = array( 'data' => array( 'product_id' => array( 1000 ), 'quantity' => array( 1 ) ) );

print_r( $cart );
echo '<br /><br />';

// Add items to the cart:
array_push( $cart['data']['product_id'], 2000 );
array_push( $cart['data']['quantity'], 2  );

print_r( $cart );
echo '<br /><br />';

// Variable with the item to delete from the cart:
$id = 1000;

// Variable to hold the length of the items in the cart
$max = count( $cart['data'] );

// Loop through the cart, and see if the id is there, and if it is, then delete $cart[$i] ?
for( $i = 0; $i < $max; $i++ )
{
foreach( $cart as $key => $value )
{
    echo $value['product_id'][$i] . '<br />';
    echo $value['quantity'][$i] . '<br />';
    // Tjek om id er i array, og slet det hvis det er:
    if( in_array( $id, $value['product_id'] ) )
    {
        echo '<p>Match!</p>';
        echo $value['product_id'][$i];
    }
}

/*
if( in_array( $id, $cart['data']['product_id'] ) )
{
    echo 'Found<br />';
    unset( $cart[$i] );
}
*/
}

echo '<br /><br />';
print_r( $cart );

How can I go about this?

/Klemme

2
Contributors
1
Reply
17
Views
3 Years
Discussion Span
Last Post by paulkd
0

overwrite line 16 (above) with this:-

$id = 1000;

$key = array_search($id, $cart['data']['product_id']);
if($key!==FALSE) {
    unset($cart['data']['product_id'][$key]);
    unset($cart['data']['quantity'][$key]);
}
print_r($cart);
die;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.