Hello. There is a code:

<? include "../cfg.php"; $select_all_raffles = mysql_query('SELECT * FROM raffles WHERE closed = "0" ORDER BY price DESC'); echo '{"raffles_games": ['; $status = "0%"; $status_text = "0 / 2"; while($row_all_raffles = mysql_fetch_array($select_all_raffles)) { if(!empty($row_all_raffles['player1']) && !empty($row_all_raffles['player2'])) { $status = "100%"; $status_text = "2 / 2"; } else if(!empty($row_all_raffles['player1']) || !empty($row_all_raffles['player2'])) { $status = "50%"; $status_text = "1 / 2"; } if($row_last_pls['id'] == $row_all_raffles['id']) { $last_or_no = ","; } $scoba = '"'; printf("{".$scoba."id_raffle".$scoba.": %s".$scoba."width_percent".$scoba.":".$scoba."%s".$scoba."width_text".$scoba.":".$scoba."%s",$row_all_raffles['id'].",", $status.$scoba.",",$status_text.$scoba."}*проблемное место*"); } echo "]}"; ?> 

The bottom line is that I want to output the lines from the database to the json line. When there was one line, everything worked, and a little later, when I did almost everything and threw more lines into the database, the lines started to appear more and json is approximately in this format:

 {"raffles_games": [{"id_raffle": 2,"width_percent":"0%","width_text":"0 / 2"}{"id_raffle": 3,"width_percent":"0%","width_text":"0 / 2"}{"id_raffle": 5,"width_percent":"0%","width_text":"0 / 2"}{"id_raffle": 9,"width_percent":"0%","width_text":"0 / 2"}{"id_raffle": 4,"width_percent":"0%","width_text":"0 / 2"}{"id_raffle": 6,"width_percent":"0%","width_text":"0 / 2"}{"id_raffle": 7,"width_percent":"0%","width_text":"0 / 2"}{"id_raffle": 8,"width_percent":"0%","width_text":"0 / 2"}]} 

The problem was that a comma is needed after each array. Well, I decided to put a comma in a problem place (code 1). But after the problem is that a comma is put at the end of each array, i.e. and after the latter (which is, in fact, an error). So tell me, guys, how can I make sure that the comma after the last array is not put? Hopefully explained intelligibly. Thank!)

  • one
    you make some kind of absolutely awful crutch ....... make an array with the necessary structure and then use json_encode , do not torture yourself - Alexey Shimansky
  • still for the general development of implode is - teran

1 answer 1

Should work

 $array2json = array(); while($row_all_raffles = mysql_fetch_array($select_all_raffles)) { if(!empty($row_all_raffles['player1']) && !empty($row_all_raffles['player2'])) { $status = "100%"; $status_text = "2 / 2"; } else if(!empty($row_all_raffles['player1']) || !empty($row_all_raffles['player2'])) { $status = "50%"; $status_text = "1 / 2"; } $raffle['id_raffle'] = $row_all_raffles['id']; $raffle['width_percent'] = $status; $raffle['width_text'] = $status_text; $array2json[] = $raffle; } echo json_encode(array('raffles_games'=>$array2json));