选择和使用JSON数组值

时间:2017-11-24 13:47:40

标签: php json xml session-variables

我目前正在开发购物应用程序,但我偶然发现了一个问题。问题是我无法从“购物车”中选择JSON值。请参阅以下代码和说明。

所以通过使用添加到购物车按钮,我正在创建购物车。购物车实际上是JSON对象。购物车的一个例子:

{"cartItems":{"2":{"id":"2","name":"Blouse","price":26.99,"size":"M","quantity":"3","total_product_price":80.97},"5":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"L","quantity":"4","total_product_price":122}},"totalPrice":202.97,"totalItems":2,"customerSelect":{"id":"1","firstname":"John","lastname":"TestStefans"}}

正如您所看到的,JSON购物车的设计是:

cart:{"cartItems":{"id":{ product information }}}

现在的问题是尝试选择“名称”和“价格”等值。这是由"id"{段引起的。但我需要那件用于从购物车中删除id的一件物品。

所以我的问题是:

我如何能够选择所有产品信息并创建foreach以将信息放入数据库/电子邮件模板中。我一直在尝试这个,但这只给了我第一个产品:

$cart_encode = json_encode($_SESSION['cart']['cartItems']);
$cartDecode = json_decode($cart_encode);
// Adding the product items
            foreach ($cartDecode as $key => $cartItem) {
                $resource->associations->cart_rows->cart_row->id_product = $cartItem->{"id"};
                $resource->associations->cart_rows->cart_row->id_product_attribute = 1;
                $resource->associations->cart_rows->cart_row->id_address_delivery = 1;
                $resource->associations->cart_rows->cart_row->quantity = $cartItem->{"quantity"};
            }

请注意我正在使用XML进行数据库输入。对于我尝试过的电子邮件模板:

$testName = $_SESSION['cart']['cartItems']['name'];
$testPrice = $_SESSION['cart']['cartItems']['price'];
$testQuantity = $_SESSION['cart']['cartItems']['quantity'];
$testTotal = $_SESSION['cart']['cartItems']['total_product_price'];

$testProduct = array(
    "Name:" => $testName,
    "Price:" => $testPrice,
    "Quantity" => $testQuantity,
    "Total" => $testTotal
);

我知道id number缺失但我无法动态地避开那一层。

我希望我的问题很清楚

一如既往。提前谢谢!

0 个答案:

没有答案