我正在嘗試爲我的網站構建一個寧靜的web服務。我有一個PHP的MySQL查詢中使用以下代碼:試圖格式化json以某種方式在PHP中使用mysql數組
function mysql_fetch_rowsarr($result, $taskId, $num, $count){
$got = array();
if(mysql_num_rows($result) == 0)
return $got;
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
$got[]=$row;
}
print_r($row)
print_r(json_encode($result));
return $got;
返回在代碼使用上述
Array ([0] => Array ([show] => Blip TV Photoshop Users TV [region] => UK [url] => http://blip.tv/photoshop-user-tv/rss [resourceType] => RSS/Atom feed [plugin] => Blip TV) [1] => Array ([show] => TV Highlights [region] => UK [url] => http://feeds.bbc.co.uk/iplayer/highlights/tv [resourceType] => RSS/Atom feed [plugin] => iPlayer (UK)))
這裏的print_r($數據)下面是它返回JSON:
[{"show":"Blip TV Photoshop Users TV","region":"UK","url":"http:\/\/blip.tv\/photoshop-user-tv\/rss","resourceType":"RSS \/ Atom feed","plugin":"Blip TV"},{"show":"TV Highlights","region":"UK","url":"http:\/\/feeds.bbc.co.uk\/iplayer\/highlights\/tv","resourceType":"RSS \/ Atom feed","plugin":"iPlayer (UK)"}]
我正在使用下面的代碼將一些項目添加到數組,然後將其轉換爲json並返回json。
$got=array(array("resource"=>$taskId,"requestedSize"=>$num,"totalSize"=>$count,"items"),$got);
使用以下代碼將其轉換爲json並將其返回。
$response->body = json_encode($result);
return $response;
這給了我下面的json。
[{"resource":"video","requestedSize":2,"totalSize":61,"0":"items"},[{"show":"Blip TV Photoshop Users TV","region":"UK","url":"http:\/\/blip.tv\/photoshop-user-tv\/rss","resourceType":"RSS \/ Atom feed","plugin":"Blip TV"},{"show":"TV Highlights","region":"UK","url":"http:\/\/feeds.bbc.co.uk\/iplayer\/highlights\/tv","resourceType":"RSS \/ Atom feed","plugin":"iPlayer (UK)"}]]
該API的消費者想要以下格式的json,我無法弄清楚如何讓它以這種方式出現。我搜索並嘗試了所有我能找到的東西,但仍然沒有得到它。我甚至還沒有開始試圖獲得XML格式化
{"resource":"video", "returnedSize":2, "totalSize":60,"items":[{"show":"Blip TV Photoshop Users TV","region":"UK","url":"http://blip.tv/photoshop-user-tv/rss","resourceType":"RSS/Atom feed","plugin":"Blip TV"},{"show":"TV Highlights","region":"UK", "url":"http://feeds.bbc.co.uk/iplayer/highlights/tv","resourceType":"RSS/Atom feed","plugin":"iPlayer (UK)"}]}
我欣賞任何和所有這方面的幫助。我已經設置了只讀訪問數據庫的副本,可以給所有的源代碼,它會幫助,我會警告你,我只是現在學習PHP,我學會了在基本,fortran 77編程,所以PHP是相當凌亂我猜會很臃腫。
OK上面關於json編碼被回答了。 API消費者也需要特殊字符「/」,因爲它是一個URL,所以不會被轉義。我嘗試了json_encode中的「JSON_UNESCAPED_SLASHES」,並得到以下錯誤。
json_encode() expects parameter 2 to be long
應用'json_decode'到所需的JSON輸出,看看你需要裝配得到同樣的 – zerkms 2012-04-11 23:47:22
我怎樣才能得到所需的JSON到PHP什麼陣列?我可以讓它成爲一個字符串然後json)解碼字符串? – Moltra 2012-04-11 23:48:38
「API的使用者希望json採用以下格式」---這是所需的格式,即以下格式。你的消費者想要的那個顯然是一個理想的 – zerkms 2012-04-11 23:49:48