【问题标题】:convert array to json from SESSION variable将数组从 SESSION 变量转换为 json
【发布时间】:2014-03-18 02:34:00
【问题描述】:

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

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

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

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

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

谢谢

【问题讨论】:

    标签: php arrays json session session-variables


    【解决方案1】:

    只需使用the built-in function json_encode:

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

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

    【讨论】:

      【解决方案2】:
         <?php
            session_start();
            $_SESSION['cart'] = array('test' => 'stuff');
            echo json_encode($_SESSION); //Prints {"cart":{"test":"stuff"}}
         ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-14
        • 2013-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多