1

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!

1
  • Before assigning $row["tip"] to $tip, see if they are equal. If not, output $row["tip"] (and a newline), and then assign to $tip. If they are, don't output. Commented May 1, 2019 at 13:20

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

how can I use $tip and $e outside foreach loop?
They are inner var of the loop scope - so you cannot. What do you need them for? why not use them in the foreach loop? You can get them also from the $arr var outside the loop if you really need to
I need to pass this result into onesignal array. $fields = array( 'data' => array("array" => "".$result_of_your_array.""), 'priority' => 10 );
Updated the answer to get the result outside the loop
get this error: Warning: array_merge(): Argument #2 is not an array $e variable seems not declared:
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.