从多维数组php中获取值



我想做多维数组,但在看了几个小时后,我很失落。我通过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转换为数组来绕过它。这是正确的做法吗?或者还有更好的吗?由于

在你的地址栏输入这些:

/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

这一行应该做什么?

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

你最好写:

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

要将key => value添加到array,您必须这样写:

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>" ;
}

相关内容

  • 没有找到相关文章

最新更新