我使用这个php代码(部分)在我的函数中生成了一个数组:
while (!$combined->EOF) {
$orders_id = $combined->fields['orders_id'];
$customers_name = $combined->fields['customers_name'];
$products_name = $combined->fields['products_name'];
$products_model = $combined->fields['products_model'];
$products_quantity = $combined->fields['products_quantity'];
$this_order_data = array(
'orders_id' => $orders_id,
'name' => $products_name,
'model' => $products_model,
'quantity' => $products_quantity,
);
if (isset($this->timeframe[$id]['combined'][$oID])) {
$this->timeframe[$id]['combined'][$oID]['products'][] = $this_order_data;
} else {
$this->timeframe[$id]['combined'][$oID]['order_id'] = $oID;
$this->timeframe[$id]['combined'][$oID]['customer_name'] = $customers_name;
$this->timeframe[$id]['combined'][$oID]['products'][] = $this_order_data;
}
$combined->MoveNext();
}
这给出了一个类似于以下示例的数组:
[6] => Array
(
[order_id] => 1910
[customer_name] => Customer A
[products] => Array
(
[0] => Array
(
[orders_id] => 1910
[name] => Product 1
[model] => P1
[quantity] => 31
)
[1] => Array
(
[orders_id] => 1910
[name] => Product 2
[model] => P2
[quantity] => 50
)
[2] => Array
(
[orders_id] => 1910
[name] => Product 3
[model] => P3
[quantity] => 20
)
)
)
[7] => Array
(
[order_id] => 1911
[customer_name] => Customer B
[products] => Array
(
[0] => Array
(
[orders_id] => 1911
[name] => Product 2
[model] => P2
[quantity] => 75
)
[1] => Array
(
[orders_id] => 1911
[name] => Product 4
[model] => P4
[quantity] => 30
)
)
)
然后我使用此代码输出代码以便在屏幕上显示
<?php
$i = 0;
foreach($timeframe['combined'] as $key => $c_data) if ($c_data['order_id'] == $c_data['products'][$i]['orders_id']){
$items = count($c_data['products']);
?>
<tr class="lineItemRow" <?php echo $rollover; ?>>
<td class="lineItemContent" align="left"><?php echo $c_data['products'][$i]['name']; ?></td>
<td class="lineItemContent" align="left"><?php echo $c_data['products'][$i]['model']; ?></td>
<td class="lineItemContent" align="right"><?php echo $c_data['products'][$i]['quantity']; ?></td>
<td class="lineItemContent" align="right"><?php echo $c_data['products'][$i]['count']; ?></td>
</tr>
<?php
if ($i == $items){
$i= 0;
}else{
$i=$i+1;
}
}
因为我不知道每个阵列中会有多少产品,所以我认为我需要获得$ c_data ['products']的计数,在循环开始之前将$ i设置为0,然后每次递增,直到达到计数值。 只有它不能那样工作。我注意到的是,$ i只会在每次移动到新订单时递增,而不是每个新产品。这显然给了我不正确的数据,因为$ i每次都没有查看数组的正确部分。
我应该如何正确地遍历'products'数组中的每个项目?
答案 0 :(得分:1)
为什么你不循环进入$ c_data ['products']?
<?php
foreach($timeframe['combined'] as $key => $c_data)
foreach($c_data as $data)
foreach($data['products'] as $product)
if ($data['order_id'] == $product['orders_id']) { ?>
<tr class="lineItemRow" <?php echo $rollover; ?>>
<td class="lineItemContent" align="left"><?php echo
$product['name']; ?></td>
<td class="lineItemContent" align="left"><?php echo
$product['model']; ?></td>
<td class="lineItemContent" align="right"><?php echo
$product['quantity']; ?></td>
<td class="lineItemContent" align="right"><?php echo
$product['count']; ?></td>
</tr>
<?php } ?>