从多维数组php获取值

时间:2016-09-06 07:26:33

标签: php arrays multidimensional-array

我想制作多维数组但是看了好几个小时之后我就迷失了。我通过AJAX从模态发送ID和数量,我希望像$_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'];
}

我试图像这样访问它:

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

但是对于第二个foreach,我得到警告,它的参数是无效的,我可以绕过将$ value转换为数组。这是正确的方法吗?还是有更好的?感谢

2 个答案:

答案 0 :(得分:2)

在地址栏中输入以下内容:

/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>';
    }
}

<强>结果:

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

答案 1 :(得分:1)

这条线应该是什么?

$_SESSION['cart'][][] = $_REQUEST['quantity'];

你最好写:

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

<强>解释

添加key =&gt; valuearray,你必须写:

array[key] = value

此处您的数组为$_SESSION['cart'],密钥为$_REQUEST['id'],您的值为$_REQUEST['quantity']。所以你必须写:

$_SESSION['cart'][$_REQUEST['id']] = $_REQUEST['quantity'];

或者,一步一步......

$array = $_SESSION['cart'];
$id = $_REQUEST['id'];
$value = $_REQUEST['quantity'] ;

$array[$key] = $value ;
$_SESSION['cart'] = $array ;

要访问它:

foreach($_SESSION['cart'] as $key => $value){
    echo "For key $key, value is $value" . "<br>" ;
}