Forum Moderators: coopster

Message Too Old, No Replies

sort array and update keys

sort array and update keys

         

drooh

9:01 pm on Nov 3, 2010 (gmt 0)

10+ Year Member



Not sure if Im going about this the correct way. But after an entry is removed from my array I am left with a hole in the keys.

for instance

Array
(
[0] => Array
(
[prod_id] => 1
[prod_name] => Mens Bungee Full
[prod_price] => 24.95
)
[2] => Array
(
[prod_id] => 1
[prod_name] => Mens Bungee Full
[prod_price] => 24.95
)
)

If I want to set the 2 to a 1 how do i do that?

As of now Im looping through the array creating a new temp array then unsetting the first and re-creating it with the temp


if(isset($_GET['remove'])){

$remove_key = $_GET['remove'];
unset($_SESSION['cart'][$remove_key]);

// manuall re-sort to assign indexes

$new_temp_array = array();

foreach($_SESSION['cart'] as $update){

$new_temp_array[] = $update;

}

unset($_SESSION['cart']);
$_SESSION['cart'] = $new_temp_array;
}

astupidname

6:50 am on Nov 4, 2010 (gmt 0)

10+ Year Member



Instead of:
unset($_SESSION['cart'][$remove_key]);

and all the rest of that code, try array_splice() [us2.php.net] :
array_splice($_SESSION['cart'], $remove_key, 1);

enigma1

12:11 pm on Nov 4, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Use the array_values function
$_SESSION['cart'] = array_values($_SESSION['cart']);
It will force an array with integer keys starting from 0.