首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用PHP在JSON中创建对象数组

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

Stack Overflow用户
提问于 2019-04-15 03:59:59
回答 1查看 19关注 0票数 0

我对php和JSON非常陌生,我有下面的代码:我也想从头开始学习所有这些东西,请给我推荐一些书。提前谢谢。

代码语言:javascript
复制
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);

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

代码语言:javascript
复制
       {"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}

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

代码语言:javascript
复制
[{
    "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"]
}]
EN

回答 1

Stack Overflow用户

发布于 2019-04-15 04:21:12

您的问题是,正如您所说的{"0":"object_deducted"}$response是索引和关联值的混合,它们将在您的json中创建

为了解决这个问题,我将$response更改为一个关联数组,这样它就可以有successdata,后者是您提取的数据的索引数组

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55679507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档