Reputation: 346
I am using this while loop in order to echo some data:
$arr = array();
while ($row = mysqli_fetch_assoc($result)) {
$tip= $row["tip"];
$name= $row["name"];
$qty= $row["qty"];
$arr = "\n".$tip. "" .$qty."x " .$name;
echo "<pre>";
print_r($arr);
echo "</pre>";
}
And getting those results:
Food 1x Hambuger
Food 1x Pizza
Food 1x Milk
Food 1x Wine
Sports 2x Shirt
Sports 1x Gloves
Sports 1x Shoes
However, this is my expected result:
Food
1x Hambuger
1x Pizza
1x Milk
1x Wine
Sports
2x Shirt
1x Gloves
1x Shoes
Should be use array unique?
Thanks!
Upvotes: 1
Views: 38
Reputation: 11642
You better extract the data differently - This way it will work even if the tip
is not ordered (AKA food, sports and then food again).
Consider:
$arr = array();
while ($row = mysqli_fetch_assoc($result)) {
$arr[$row["tip"]][] = $row["qty"] . "x " . $row["name"];
}
foreach($arr as $tip => $values) {
echo $tip . PHP_EOL;
foreach($values as $e) {
echo $e . PHP_EOL;
}
}
Edited:
as you want it outside use:
$arr = array();
while ($row = mysqli_fetch_assoc($result)) {
$arr[$row["tip"]][] = $row["qty"] . "x " . $row["name"];
}
$res = array(); // init empty array for result
foreach($arr as $tip => $values) {
$res[] = $tip;
$res = array_merge($res, $e)
}
echo implode("\n", $res);
Now $res
is available outside the loop
Upvotes: 1