我使用foreach制作包含来自“sale”行json_decode($row['sale'])
的数据的表格,现在分别显示每个条目,我想要做的是将每个条目[product_id]
显示为一个并且汇总所有具有相同id的条目的[num],sum [product_pcs],sum [price_per_pcs]并将其显示为一行。
json_decode($行[ '销售'):
Array ( [0] => stdClass Object ( [stock_id] => 501 [product_id] => 7 [product_pcs] => 1120 [price_per_pcs] => 1.17 [num] => 1) [1] => stdClass Object ( [stock_id] => 500 [product_id] => 7 [product_pcs] => 1120 [price_per_pcs] => 1.17 [num] => 1 ) [2] => stdClass Object ( [stock_id] => 497 [product_id] => 3 [product_pcs] => 600 [price_per_pcs] => 1,1 [num] => 1 ) [3] => stdClass Object ( [stock_id] => 496 [product_id] => 3 [product_pcs] => 600 [price_per_pcs] => 1,1 [num] => 1 ) [4] => stdClass Object ( [stock_id] => 526 [product_id] => 25 [product_pcs] => 1120 [price_per_pcs] => 1.22 [num] => 1 ) [5] => stdClass Object ( [stock_id] => 525 [product_id] => 7 [product_pcs] => 1120 [price_per_pcs] => 1.17 [num] => 1 ) )
我以这种方式显示收到的数据:
<table>
<thead>
<tr>
<th>No</th>
<th>Product ID</th>
<th>Price Per Piece</th>
<th>Product pcs</th>
<th>Total products</th>
<?php
$count = 1;
$sale = json_decode($row['sale']);
foreach ($sale as $product):
?>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $count++;?>.</td>
<td><?php echo $product->product_id; ?></td>
<td><?php echo $product->price_per_pcs;?></td>
<td><?php echo $product->product_pcs; ?></td>
<td><?php echo $product->num; ?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
我将非常感激。
答案 0 :(得分:1)
最好的方法是更改原始SQL查询,但由于此时缺少该信息,您可以使用以下内容创建一个包含所需总和的新数组:
<table>
<thead>
<tr>
<th>No</th>
<th>Product ID</th>
<th>Price Per Piece</th>
<th>Product pcs</th>
<th>Total products</th>
</tr>
</thead>
<tbody>
<?php
$sale = json_decode($row['sale']);
$sum = array(); // INITIATE NEW ARRAY WITH SUMS
// SUM UP VALUES IN A NEW ARRAY...
foreach ($sale as $product){
// CHECK IF ITEM IS SET TO PREVENT "Undefined offset" ERRORS...
if (!isset($sum[$product->product_id])) {
// INITIATE ARRAYS.. THE PRODUCT ID IS USED AS ARRAY KEY
$sum[$product->product_id]['price_per_pcs'] = $product->price_per_pcs;
$sum[$product->product_id]['product_pcs'] = $product->product_pcs;
$sum[$product->product_id]['product_num'] = $product->num;
} else { // ARRAYS ALREADY SET.. USE ASSIGNMENT OPERATORS TO SUM UP THE VALUES
$sum[$product->product_id]['price_per_pcs'] += $product->price_per_pcs;
$sum[$product->product_id]['product_pcs'] += $product->product_pcs;
$sum[$product->product_id]['product_num'] += $product->num;
}
}
// LOOP THROUGH SUMS ARRAY...
$count = 1;
foreach ($sum as $key=>$val){
?>
<tr>
<td><?php echo $count++;?>.</td>
<td><?php echo $key; ?></td>
<td><?php echo $val['price_per_pcs'];?></td>
<td><?php echo $val['product_pcs']; ?></td>
<td><?php echo $val['product_num']; ?></td>
</tr>
<?php } ;?>
</tbody>
</table>
请告诉我这是否适合您..或者我是否可以帮助您解决任何其他问题。