Pedro Silva
Pedro Silva

Reputation: 33

while loop with if statement not working properly

hi i have the following while loop :

while ($row = mysqli_fetch_array($result2)){

    $elem_filho = $row['itempt_dim'];

    $marcas = "{name: " . "'" . $elem_filho . "'" . ", color: " . "'" . $cor_alea . "'" . ", size: 1";

    if (mysqli_num_rows($result2)) {
      $dif = "},";
    }

    else {
      $dif = "}]";
    }

    $vlk = $marcas . $dif;
    print_r($vlk);

  }

the thing is i had similar code and it worked this way, but the output is alway }, and i want the last item of the query to end with }] i can't see what i am doing wrong

thanks in advance

Upvotes: 0

Views: 33

Answers (1)

u_mulder
u_mulder

Reputation: 54831

With json_encode you code is simplified to:

$vlk = [];
while ($row = mysqli_fetch_array($result2)) {
    $vlk[] = [
        'name' => $row['itempt_dim'],
        'color' => $cor_alea,
        'size' => 1,
    ];
}
print_r(json_encode($vlk));

Upvotes: 2

Related Questions