Json不会在php中响应我的数组

时间:2015-06-07 13:28:29

标签: php android mysql json android-json

我正在尝试从我的数据库中获取多行,然后使用json对其进行编码,以便我可以在我的Android应用程序中访问它们。我已经成功编码了一个对象,但我找不到用数组做同样的方法。我的代码如下:

if($ tag =='friends'){

    $id = $_POST['id'];

    $friends = $db->getMyFriends($id);
    if ($friends != false) {
        // friends found          
        $result[] = array();
            while($row = mysql_fetch_assoc($friends)){
                $response[ "error"] = FALSE;
                $result[] = array(
                $response["friends"]["unique_id"] = $row["unique_id"],
                $response["friends"]["name"] = $row["name"],
                $response["friends"]["email"] = $row["email"]);
            }

        echo json_encode($response);
    }

来自getMyFriends($ id)的代码我已经测试过,它运行正常。它返回:

$ result = mysql_fetch_array($ result);
                return $ result;

使用rest客户端传递参数时: 标签:朋友们 id:$ id

这是我得到的json响应: {     “tag”:“我的朋友”,     “错误”:错误 } ,但没有实际的数据库数据。

如果有人知道我做错了什么,我真的很感激,我已经在网上浏览了几个小时了。

2 个答案:

答案 0 :(得分:0)

我试过这个并且有效。

if($tag=='friends'){ 
$id = $_REQUEST['id'];
$friends = $db->getMyFriends($id);
if ($friends != false) {
// friends found          
$result[] = array();
while($row = mysql_fetch_assoc($friends)){
    $response[ "error"] = FALSE;
    $result[] = array(
    $response["friends"]["unique_id"] = $row["id"],
    $response["friends"]["name"] = $row["name"],
    $response["friends"]["email"] = $row["email"]
    );
}

echo json_encode($result);
}
}

答案 1 :(得分:0)

如果getMyFriends已经有$result = mysql_fetch_array($result);你不需要再次获取。

你可以简单地说:

$friends = $db->getMyFriends($id);
echo json_encode($friends);

但是只返回一个朋友,如果你想从getMyFriends中删除$result = mysql_fetch_array($result);并返回纯mysql_result,那么执行以下操作:

 $result = array();
 while($row = mysql_fetch_assoc($friends)){
    array_push($result,$row);
 }
 echo json_encode($result);