从会话数组中删除项后重新排序数组键[重复]

问题描述:

This question already has an answer here:

I have $_SESSION['items'] to stored cart items as structure below:

print_r($_SESSION['items']):

Array
(
[0] => Array
    (
        [p_name] => Germany Fully Synthetic Engine Oil 5w40, 4L
        [p_code] => 15177651
        [p_coverImg] => 13-1460446338-kMTXa.jpg
        [p_id] => 13
        [p_price] => 126.00
        [p_qty] => 2
    )

[1] => Array
    (
        [p_name] => BetterBody Foods Organic Cold Pressed Extra Virgin Coconut Oil
        [p_code] => 15599414
        [p_coverImg] => 9-1460445708-6XlfS.jpg
        [p_id] => 9
        [p_price] => 278.40
        [p_qty] => 5
    )

[2] => Array
    (
        [p_name] => X-Dot Motorbike Helmet G88 + Bogo Visor (Tinted)
        [p_code] => 2102649
        [p_coverImg] => 12-1460446199-wI5qx.png
        [p_id] => 12
        [p_price] => 68.00
        [p_alt-variation-1] => Blue
        [p_alt-variation-2] => L
        [p_qty] => 2
    )

)

so to remove item I use unset($_SESSION['items'][$arr_key]);

let says I unset($_SESSION['items'][0]); from above array, after all I print_r($_SESSION['items']), the array key is not starting with [0] anymore:

Array
(
[1] => Array
    (
        [p_name] => BetterBody Foods Organic Cold Pressed Extra Virgin Coconut Oil
        [p_code] => 15599414
        [p_coverImg] => 9-1460445708-6XlfS.jpg
        [p_id] => 9
        [p_price] => 278.40
        [p_qty] => 5
    )

[2] => Array
    (
        [p_name] => Wonder Belt Set (2pcs)
        [p_code] => 33134567
        [p_coverImg] => 2-1460445193-vZwGV.jpg
        [p_id] => 2
        [p_price] => 199.00
        [p_qty] => 1
    )

)

how can I restore these session array stating with key 0 again after remove certain item?

</div>

You should use array_values as

array_values($_SESSION['items']);

Suggest you to use array_values() to resort keys. An example:

$array = [1, 2, 3];
unset($array[0]);

print "<pre>";
print_r($array);
print "</pre>";

Output:

Array
(
    [1] => 2
    [2] => 3
)

// Resort keys using array_values
$array = array_values($array);
print "<pre>";
print_r($array);
print "</pre>";

Output after using array_values:

Array
(
    [0] => 2
    [1] => 3
)

use array_values()

array_values() returns all the values from the array and indexes the array numerically.

http://php.net/manual/en/function.array-values.php