dongmubi4444 2016-09-06 07: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 08: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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料