从SESSION变量将数组转换为json

时间:2014-03-17 18:31:35

标签: php arrays json session session-variables

我正在尝试转换一个数组,我将一些'产品'($ _SESSION ['cart'])存储为JSON格式,但这对我来说是不可能的

$ _SESSION ['cart']变量的结构是

$_SESSION['cart']['id_product']['quantity']

我正在使用此代码获取每个产品,我想我可以从这里获得一个数组

foreach($_SESSION['cart'] as $id_product => $quantity) { 
code
}

由于

2 个答案:

答案 0 :(得分:3)

只需使用the built-in function json_encode

$myjson = json_encode($_SESSION['cart']);

替换您想要的任何变量,例如$_SESSION['cart']['id_product']['quantity']

答案 1 :(得分:1)

   <?php
      session_start();
      $_SESSION['cart'] = array('test' => 'stuff');
      echo json_encode($_SESSION); //Prints {"cart":{"test":"stuff"}}
   ?>
相关问题