2

我正在尝试为我的网站构建一个宁静的网络服务。我有一个使用以下代码的 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;  

它使用上面代码中的 print_r($data) 返回以下内容

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) ) ) 

这是它返回的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
4

1 回答 1

0

你的$result线应该看起来像

$result=array(
    "resource"=>$taskId,
    "requestedSize"=>$num,
    "totalSize"=>$count,
    "items" => $got
);
于 2012-04-11T23:48:33.417 回答