I have a multidimensional array, where I want to group values together based on a value they have in common. Basically I'm creating a program where you can order parts from different suppliers and when you submit the order an array get created with all the values.
After that I need to create groups of parts with the same supplier so I can create one email for each supplier. I have replicated this problem on a smaller scale and trying to create tables for each supplier first.
This is the array I'm using
$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',
)
);
I thought maybe if I would group them first based on supplier I would have more succes. I did that as follows
$arr = array();
foreach($result as $key => $value) {
$arr[$value['supplier']][$key] = $value;
}
ksort($arr, SORT_NUMERIC);
Than I started creating the tables like this
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>';
But this creates just one table. And when I change the operator to ==
it creates 5 separate tables.
/edit
Perfect outcome would be
<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>
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>';
}