我有一个多维数组,我想根据它们共同的值将值组合在一起。基本上我正在创建一个程序,您可以在其中订购来自不同供应商的零件,当您提交订单时,将使用所有值创建一个数组。
之后,我需要使用相同的供应商创建零件组,以便为每个供应商创建一个电子邮件。我已经在较小的规模上复制了这个问题,并试图首先为每个供应商创建表格。
这是我正在使用的数组
$result = Array(
0 => Array (
'supplier' => 'Supplier 1',
'descr' => 'Product 1',
'id' => '123',
'quantity' => '5',
),
1 => Array (
'supplier' => 'Supplier 1',
'descr' => 'Product 2',
'id' => '345',
'quantity' => '1',
),
2 => Array (
'supplier' => 'Supplier 2',
'descr' => 'Product 3',
'id' => '567',
'quantity' => '10',
),
3 => Array (
'supplier' => 'Supplier 1',
'descr' => 'Product 4',
'id' => '789',
'quantity' => '1',
),
4 => Array (
'supplier' => 'Supplier 3',
'descr' => 'Product 5',
'id' => '111',
'quantity' => '6',
),
5 => Array (
'supplier' => 'Supplier 4',
'descr' => 'Product 6',
'id' => '222',
'quantity' => '30',
)
);
我想也许如果我先根据供应商将它们分组,我会有更多的成功。我这样做了如下
$arr = array();
foreach($result as $key => $value) {
$arr[$value['supplier']][$key] = $value;
}
ksort($arr, SORT_NUMERIC);
比我开始创建这样的表
echo '<table>';
foreach($arr as $id) {
foreach($id as $key => $value) {
echo '<tr>';
echo '<td>'.$value['supplier'].'</td>';
echo '<td>'.$value['descr'].'</td>';
echo '<td>'.$value['id'].'</td>';
echo '<td>'.$value['quantity'].'</td>';
echo '</tr>';
// different supplier so start new table
if(current($value['supplier']) != next($value['supplier'])){
echo '</table><table>';
}
}
}
echo '</table>';
但这只会创建一个表。当我将操作符更改为==
时,它会创建5个单独的表。
/编辑
完美的结果将是
<table>
<tr>
<td>Supplier 2</td>
<td>Product 3</td>
<td>567</td>
<td>6</td>
</tr>
</table>
<table> <!-- One table with 3 different parts but same supplier -->
<tr>
<td>Supplier 1</td>
<td>Product 1<td>
<td>123</td>
<td>5</td>
</tr>
<tr>
<td>Supplier 1</td>
<td>Product 2</td>
<td>345</td>
<td>1</td>
</tr>
<tr>
<td>Supplier 1</td>
<td>Product 4</td>
<td>789</td>
<td>1</td>
</tr>
</table>
<table>
<tr>
<td>Supplier 3</td>
<td>Product 5</td>
<td>111</td>
<td>30</td>
</tr>
</table>
<table>
<tr>
<td>Supplier 4/td>
<td>Prodcut 6</td>
<td>222</td>
<td>10</td>
</tr>
</table>
答案 0 :(得分:1)
Change your loop accordingly
foreach($arr as $id) {
foreach($id as $key => $value) {
echo '<tr>';
echo '<td>'.$value['supplier'].'</td>';
echo '<td>'.$value['descr'].'</td>';
echo '<td>'.$value['id'].'</td>';
echo '<td>'.$value['quantity'].'</td>';
echo '</tr>';
}
// different supplier so start new table
echo '</table><table>';
}