开发者

JSON Encode is dropping every other value

I have a php script constructed to respond to an ajax call for data, which is two columns from a mySQL database of the form "Date","Value", with dates following a weekly interval.

Ultimately I want to return the result to the calling page by setting a session variable to hold the series data in a json encoded array. I'm not sure if this is the most appropriate method as I'm following a bit of mish-mash of online example and tutorials, so I'm just hopinig I'm on the right tracks.

So far I can render the results into a html table on the calling page as follows which gives me the results that I would expect:

echo "<table border='1'>
<tr>
<th>Date</th>
<th>Value</th>
</tr>";

while($row=mysql_fetch_array($res_Data)) { 
    echo "<tr>";
   echo "<td>".$row['Date']."</td>";
   echo "<td>".$row['Va开发者_如何学Pythonlue']."</td>";
   echo "<tr>";  


} 
echo "</table>";

This gives me the following table (copied here without the border):

Date       Value 
2009-07-12 47.09 

2009-07-19 45.48 

2009-07-26 87.03 

2009-08-02 59.96 

2009-08-09 52.82 

2009-08-16 29.20 

However, when I try to encode the data into a JSON array so that it can be later manipulated by the calling page every other value in the series is dropped. T

As an intermediate step towards creating the final array object I am using the code below which simply encodes and echoes each row of the msql query, having first reset the pointer.

mysql_data_seek ($res_Data, 0);

while ($row=mysql_fetch_array($res_Data)) { 
      echo json_encode(mysql_fetch_array($res_Data,MYSQL_NUM))."<br/>";
}

This results in the following output where every other week is dropped:

["2009-07-19","45.48"]
["2009-08-02","59.96"]
["2009-08-16","29.20"]
["2009-08-30","99.35"]
["2009-09-13","99.35"]
["2009-09-27","17.17"]
["2009-10-11","276.64"]
["2009-10-25","336.03"]
["2009-11-08","439.28"]
["2009-11-22","383.82"]
["2009-12-06","512.04"]
["2009-12-20","796.64"]
["2010-01-03","1056.55"]

Does anyone have any ideas why this might be happening?

Ps I am something of a noobie so it's probably glaringly obvious.

Thanks


Problem is that your while loop is fetching a row and then in your json_encode call, the code is fetching a new row.

You should use the $row that you fetched in the json_encode call.

while ($row=mysql_fetch_array($res_Data,MYSQL_NUM)) {
    echo json_encode($row)." ";
}


The right code is:

while ($row=mysql_fetch_array($res_Data,MYSQL_NUM)) { 
    echo json_encode($row))."
"; }

Every time you call the mysql_fetch_array the row is fetched.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜