【问题标题】:php re-sort array key after remove item from session array [duplicate]从会话数组中删除项目后,php重新排序数组键[重复]
【发布时间】:2016-04-16 04:10:56
【问题描述】:

我有 $_SESSION['items'] 来存储购物车项目,结构如下:

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
    )

)

所以要删除我使用unset($_SESSION['items'][$arr_key]);的项目

从上面的数组说我unset($_SESSION['items'][0]);,毕竟我print_r($_SESSION['items']),数组键不再以[0]开头:

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
    )

)

如何在删除某些项目后再次使用密钥 0 恢复这些会话数组?

【问题讨论】:

    标签: php arrays session


    【解决方案1】:

    你应该使用array_values作为

    array_values($_SESSION['items']);
    

    【讨论】:

    • 如何检查$_SESSION['items']是否不再包含元素?
    【解决方案2】:

    建议您使用array_values() 来使用密钥。一个例子:

    $array = [1, 2, 3];
    unset($array[0]);
    
    print "<pre>";
    print_r($array);
    print "</pre>";
    

    输出:

    Array
    (
        [1] => 2
        [2] => 3
    )
    
    // Resort keys using array_values
    $array = array_values($array);
    print "<pre>";
    print_r($array);
    print "</pre>";
    

    使用array_values后的输出:

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

    【讨论】:

      【解决方案3】:

      使用 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

      【讨论】:

        猜你喜欢
        • 2016-10-01
        • 1970-01-01
        • 2021-11-12
        • 2021-01-27
        • 2016-01-24
        • 2018-01-18
        • 2011-02-21
        • 1970-01-01
        • 2016-07-30
        相关资源
        最近更新 更多