dongmubi4444 2016-09-05 23:26
浏览 8
已采纳

从多维数组php获取值

I would like to make multidimensional array but after looking on it for hours I am quite lost. I am sending ID and quantity from modal via AJAX, and I want to store it like this $_SESSION['cart'] =>array(here should be IDs => and each ID is pointing to its quantity)

if(!isset($_SESSION['cart'])){
    $_SESSION['cart'] = array(array());
}

if(isset($_REQUEST['id'])){
    $_SESSION['cart'][] = $_REQUEST['id'];
    $_SESSION['cart'][][] = $_REQUEST['quantity'];
}

I am trying to access it like that:

foreach($_SESSION['cart'] as $value){
    //var_dump($value);
    //echo "<br>";
    foreach($value as $item){
        var_dump($item);
        echo "<br>";
    }
}

But for second foreach I get warning that its argument is invalid, which I can bypass with converting the $value to array. Is this the right way to do it ? or is there any better ? Thanks

  • 写回答

2条回答 默认 最新

  • drsh30452 2016-09-06 00:34
    关注

    Type these in your address bar:

    /path/to/your/file.php?id=10&quantity=20
    /path/to/your/file.php?id=11&quantity=30
    /path/to/your/file.php?id=12&quantity=15
    /path/to/your/file.php?id=10&quantity=80
    

    file.php

    session_start();
    
    if(!isset($_SESSION['cart'])){
    $_SESSION['cart']=array();
    }
    
    
    if(isset($_REQUEST['id'])){
        foreach ($_SESSION['cart'] as $index => $item) {
            if (  array_key_exists($_REQUEST['id'],$item)   ) {
                $_SESSION['cart'][$index][$_REQUEST['id']] = $_REQUEST['quantity'];
                $flag=1;
                break;
            }       
        }
        if ($flag==0) {
            $_SESSION['cart'][] = array($_REQUEST['id'] => $_REQUEST['quantity']);
        }   
    }
    
    
    foreach ($_SESSION['cart'] as $index => $item) {
        foreach ($item as $id => $quantity) {
            echo 'id is :'.$id.', quantity is:'.$quantity.'<br>';
        }
    }
    

    Result:

    id is :10, quantity is:80(20 previous)
    id is :11, quantity is:30
    id is :12, quantity is:15
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部