Hi,
I have an array I want to explode as bellow:
ID Name Breakfast
1 Jack Coffee
2 Jill Coffee
3 Jack Pancake
4 John Ham
5 Jack Bun
6 Jack Waffle
7 John Egg
And the result I want displayed will look like this:
Name Breakfast
Jack Coffee
Pancake
Bun
Waffle
Jill Coffee
John Ham
Egg
Here’s the code I’ve been experimenting so far.
$query = "SELECT * FROM breakfast GROUP BY Name ASC";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$array = array($row['Name']);
foreach($array as $key => $name) {
$key = 0;
if($row['Name'] == $name) {
echo "<div id='left'>";
echo $row['Name'];
echo "</div>";
echo "<div id='right'>";
echo $row['Breakfast'] . "<br />";
echo "</div>";
}
$key++;
}
The problem is the result displayed as bellow:
Name Breakfast
Jack Coffee
Jill Coffee
John Ham
How can I solve this problem?
Thanks in advance
sparek
October 5, 2011, 7:32pm
2
I may be wrong with this, but would the following code work?
$query = "SELECT * FROM breakfast GROUP BY Name ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<div id='left'>";
echo $row['Name'];
echo "</div>";
echo "<div id='right'>";
echo nl2br($row['Breakfast']);
echo "</div>";
}
while ($row = mysql_fetch_array($result)) {
$orders[] = $row;
}
$order_placed = array();
foreach ( $orders AS $order ) {
$order_placed["{$order['name']}"][] = $order['breakfast'];
}
echo "
<table>
<tr>
<th>Name</th>
<th>Breakfast</th>
</tr>
";
foreach ( $order_placed AS $key => $value ) {
$count=count($value);
echo "
<tr>
<td rowspan='$count'>$key</td>";
foreach ( $value AS $breakfast => $name ) {
echo " <td>{$name}</td></tr>";
}
}
echo '</table>';
1 Like
r937
October 5, 2011, 8:02pm
4
ketting00:
The problem is the result displayed as bellow:
Name Breakfast
Jack Coffee
Jill Coffee
John Ham
How can I solve this problem?
remove the GROUP BY clause
To display all of the breakfast items for a name all together you need ORDER BY instead of GROUP BY
Struggled hard with the method SpacePhoenix suggested but the result remains the same… sigh.
r937 was right, but it displays only one row.
ketting00:
Struggled hard with the method SpacePhoenix suggested but the result remains the same… sigh.
r937 was right, but it displays only one row.
Retry SpacePhoenix’s code, with the modified query. Right now you’re displaying only one row, because in your original code you only retrieve one row from the result set ($row = mysql_fetch_array($result))
Thanks all, it works now, with modification…