使用PHP在JSON中创建对象数组

时间:2019-04-14 19:59:59

标签: php json

我是php和JSON的新手,我有以下代码: 我也想从头开始学习所有这些东西,请为我推荐一些书籍。预先感谢。

if (mysqli_num_rows($result) > 0) {
// looping through all results
// products node
$response = array();



while ($row = mysqli_fetch_array($result)) {
    // temp user array
    $treklocations = array();
    $treklocations["id"] = $row["id"];
    $treklocations["name"] = $row["name"];
    $treklocations["description"] = $row["description"];
    $treklocations["path"] = $row["path"];
    $treklocations["difficulty"] = $row["difficulty"];
    $treklocations["test"] = $row["test"];


    // push single product into final response array
    array_push($response, $treklocations);
}
// success
$response["success"] = 1;

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

这将产生以下格式的输出:

       {"0":
    {"id":"1"
    ,"name":"Rajmachi"
    ,"description":"Rajmachi Trek"
    ,"path":"http:\/\/192.168.1.105\/Images\/TrekLocations\/1467881880_rajmachi-fort-top-area.jpg"
    ,"difficulty":"Hard"
    ,"test":"Test"
    }
   ,"success":1}

但是我想要以这种格式输出:

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

1 个答案:

答案 0 :(得分:0)

您的问题是$response是由索引和关联值组成的,它们会像您所说的{"0":"object_deducted"}在json中创建

为解决此问题,我将$response更改为一个关联数组,以便它可以具有successdata,这是您获取的数据的索引数组

if (mysqli_num_rows($result) > 0) {
    // create an associative array
    $response = [
        'data' => [],
        'success' => 1
    ];

    while ($row = mysqli_fetch_array($result)) {
        // add an associative array into our indexed array (data)
        // $response['data'][] means add new value to the array ( key would be index number )
        $response['data'][] = [
            'id'          => $row["id"],
            'name'        => $row["name"],
            'description' => $row["description"],
            'path'        => $row["path"],
            'difficulty'  => $row["difficulty"],
            'test'        => $row["test"]
        ];
    }

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