| remove last seperator from array while loop
|
Chunter

msg:4437921 | 11:31 am on Apr 6, 2012 (gmt 0) | Hi, I'm having an issue, I'm trying to display mysql data with a php query in some javascript to display a chart. this is my php:
$query = "SELECT * FROM stats"; $result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){ echo $row['values'] . ", "; }
The return generates the following: 10000, 20000, 15000, 5000, 20000, 23000, 10000, That result has to remove the last ", " so the new result is: 10000, 20000, 15000, 5000, 20000, 23000, 10000 Can someone plz help? Thanks
|
Frank_Rizzo

msg:4437951 | 12:57 pm on Apr 6, 2012 (gmt 0) | Two ways to do this. a) Echo the comma before except on the first instance b) Build the echo string then strip the last comma a)
$query = "SELECT * FROM stats"; $result = mysql_query($query) or die(mysql_error());
$row_count = 0; while($row = mysql_fetch_array($result)){ if($row_count > 0) { echo ", "; } $row_count++; echo $row['values']; }
This will not echo the first comma because it is the the first row, then echo the data, then for each subsequent row a comma and data. b)
$query = "SELECT * FROM stats"; $result = mysql_query($query) or die(mysql_error()); $data = '';
while($row = mysql_fetch_array($result)){ $data .= $row['values'] . ", "; } $data = substr(trim($data), 0, -1); echo $data;
This builds the data string and then before printing it trims (to remove the blank space at the end), and then chops off the last character (the comma)
|
Chunter

msg:4437966 | 1:51 pm on Apr 6, 2012 (gmt 0) | Thanks for the quick reply, however I think something is going wrong. I took over both methods and both generate this error: Notice: Undefined index: values in H:\xampp\htdocs\stats\highcharts.php on line 121 What am I doing wrong plz? thx
|
Frank_Rizzo

msg:4438011 | 3:37 pm on Apr 6, 2012 (gmt 0) | What is in line 121 ?
|
rocknbil

msg:4438049 | 4:34 pm on Apr 6, 2012 (gmt 0) | I like to use option b with preg_replace. :-) It's less lines of code (no counter and if's) and executes a mod on the output once. $data = preg_replace('/,\s+$/','',$data);
|
Chunter

msg:4438074 | 5:31 pm on Apr 6, 2012 (gmt 0) | Thanks for all the help it works perfect now
|
|
|