【问题标题】:json_decode, foreach only return one row from json string [duplicate]json_decode, foreach 只返回 json 字符串中的一行
【发布时间】:2018-01-23 18:28:12
【问题描述】:

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

[{"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>

【问题讨论】:

    标签: php mysql arrays json foreach


    【解决方案1】:

    你正在覆盖$x

    替换

    $x = $item;
    

    $x[] = $item;
    

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

    【讨论】:

    • 如果我将 $x = $item 替换为 $x[] = $item;我得到未定义的索引:数量和大小。 “初始化 $x = [];”到底是什么意思?
    • 你用的是什么版本的php?如果您使用的是早于 7.0 的版本,则必须将变量初始化为 $x = array();
    • 我使用的是 5.6。好的,我明白了,但在哪个 foreach 循环之前?我切换到 php 7.1.7 会发生什么?我必须使用数组吗?
    • 这里的问题是$x 现在不同了。你需要调试一下,看看为什么array_merge 没有给你正确的数据。
    • 我做了一个 var_dump:$products[] = array_merge($x,$p);var_dump($x); 它只显示一个项目。但是如果我做一个 var_dump "$products = array();"它显示了这两个项目。所以出于某种原因,$x 只给了我字符串中的一项
    猜你喜欢
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 2018-02-09
    • 2020-01-20
    相关资源
    最近更新 更多