【问题标题】:JSON Output ArrayJSON 输出数组
【发布时间】:2015-01-24 21:47:52
【问题描述】:

我正在尝试以如下格式输出我的 JSON:http://api.androidhive.info/json/movies.json,但我不确定如何通过我的 PHP 输出代码完成此操作。现在,它在顶部显示“post”,是一张我不知道如何成功删除的地图,在这里看到:http://shipstudent.com/complaint_desk/androidfriendsList.php?username=noah。如果您需要更多信息,请告诉我。

PHP:

$rows = $stmt->fetchAll();


if ($rows) {

    $response["posts"]   = array();

    foreach ($rows as $row) 
    {
        $post = array();
        $post["username"] = $row["username"];
        $post["profile_picture"] = $row["profile_picture"];

        array_push($response["posts"], $post);
    }

    // echoing JSON response
    echo json_encode($response);


} else 
{   
    die(json_encode($response));
}

JSON:

{
    "posts": [
        {
            "username": "noah",
            "profile_picture": "https://shipstudent.com/animal/appphotos/978321177.jpg"
        },
        {
            "username": "e",
            "profile_picture": "https://shipstudent.com/complaint_desk/appphotos/owl.jpeg"
        },
    ]
}

所需格式:

[{
        "title": "Dawn of the Planet of the Apes",
        "image": "http://api.androidhive.info/json/movies/1.jpg",
        "rating": 8.3,
        "releaseYear": 2014,
        "genre": ["Action", "Drama", "Sci-Fi"]
    },
    {
        "title": "District 9",
        "image": "http://api.androidhive.info/json/movies/2.jpg",
        "rating": 8,
        "releaseYear": 2009,
        "genre": ["Action", "Sci-Fi", "Thriller"]
    },

【问题讨论】:

    标签: php android arrays json


    【解决方案1】:
    $rows = $stmt->fetchAll();
    
    $response = [];
    
    foreach ($rows as $row) {
        $post = [
            "username" => $row["username"],
            "profile_picture" => $row["profile_picture"]
        ];
        $response[] = $post;
    }
    
    echo json_encode($response);
    

    【讨论】:

    • 几乎,我在 $response = []; 处不断收到错误“语法错误,意外'['”
    • 你的 php 版本是多少?如果小于 5.4,则使用旧的数组语法:$response = array();$post = array("username" => $row["username"], "profile_picture" => $row["profile_picture"]);
    • 而我的PHP版本是5.5
    【解决方案2】:
    $response = array();
    
    foreach ($rows as $row) 
    {
        $post = array();
        $post["title"] => // define title;
        $post["image"] => // define image;
        $post["rating"] => // define rating;
        $post["releaseYear"] => // define releaseYear;
        $post["genre"] => // define genre, must be array();
        array_push($response, $post);
    }
    

    【讨论】:

    • 这行不通,因为它在那里的每一行都说意外 => 并且在删除它时,服务器会说意外变量...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 2017-10-17
    • 2017-04-12
    • 2021-02-19
    • 2016-12-05
    • 2021-10-03
    相关资源
    最近更新 更多