gpt4 book ai didi

php - json_decode, foreach 只从 json 字符串返回一行

转载 作者:行者123 更新时间:2023-11-29 06:55:50 24 4
gpt4 key购买 nike

在我的“购物车”表“items”列中,我存储 json_encoded 字符串。我解码、循环并将它们作为数组抓取。只要商品具有不同的产品 ID,它就可以正常工作:

[{"id":"56","size":"Small","quantity":"1"},{"id":"53","size":"Medium","quantity":"2"}]

但是当商品具有相同的产品 ID 时,它只显示 json 字符串中的最后一个,在本例中为“大”:

[{"id":"53","size":"Small","quantity":"1"},{"id":"53","size":"Large","quantity":"2"}]

我为产品创建了一个var_dump,它说这两项都在那里,但就像我说的,它只显示输出中的最后一项。

$txn_id = sanitize((int)$_GET['txn_id']);
$txnQuery = $db->query("SELECT * FROM transactions_alternative WHERE id = '{$txn_id}'");
$txn = mysqli_fetch_assoc($txnQuery);
$cart_id = $txn['cart_id'];
$cartQ = $db->query("SELECT * FROM cart WHERE id = '{$cart_id}'");
$cart = mysqli_fetch_assoc($cartQ);
$items = json_decode($cart['items'],true);
$idArray = array();
$products = array();var_dump($items);
foreach($items as $item){
$idArray[] = $item['id'];
}
$ids = implode(',',$idArray);
$productQ = $db->query("SELECT i.id as 'id', i.title as 'title', c.id as 'cid', c.category as 'child', p.category as 'parent'
FROM products i
LEFT JOIN categories c ON i.categories = c.id
LEFT JOIN categories p ON c.parent = p.id
WHERE i.id IN ({$ids})");
while($p = mysqli_fetch_assoc($productQ)){

foreach($items as $item){
if($item['id'] == $p['id']){
$x = $item;
continue;
}
}
$products[] = array_merge($x,$p);var_dump($products);
}
?>
<h2 class="text-center">Rendelés részletei</h2>
<div class="col-md-12">
<h3 class="text_center">Rendelt termékek</h3>
<table class="table table-condensed table-bordered table-striped">
<thead>
<th>Rendelt mennyiség</th><th>Termék neve</th><th>Kategória</th><th>Opció</th>
</thead>
<tbody>
<?php foreach($products as $product): ?>
<tr>
<td><?=$product['quantity'];?> db</td>
<td><?=$product['title'];?></td>
<td><?=$product['parent'].' / '.$product['child'];?></td>
<td><?=$product['size'];?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>

最佳答案

您正在覆盖$x

替换

$x = $item;

$x[] = $item;

并在foreach循环之前初始化$x = [];

关于php - json_decode, foreach 只从 json 字符串返回一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45699546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com