简体   繁体   English

从PHP / MySQL自定义JSON数据的格式

[英]Customizing the format of JSON data from PHP/MySQL

I have a webservice which gives data as json form mysql database. 我有一个web服务,它以json形式的mysql数据库形式提供数据。

PHP webservice PHP Web服务

<?php
    $conn = mysql_connect('localhost','root','');
    mysql_select_db('db', $conn);
    $query = mysql_query("SELECT id,group FROM faq");
    //$query content is:
    // Array ([id]=>faq1 [group]=>hardware) Array ([id]=>faq2 [group]=>software) 

    $faq = array();
    while($row = mysql_fetch_assoc($query)) {
        $faq[] = $row // <= ????????
    }

    header('Content-type: application/json');
    return json_encode($faq);
?>

JSON output that I get 我得到的JSON输出

[
    {
        "id": "faq1",
        "group": "hardware"
    },
    {
       "id": "faq2",
       "group": "software"
    }
]

JSON output that I want to have 我想要的JSON输出

[
    {
        "id": "faq1",
        "group": {
            "id": "hardware"
        }
   },
   {
       "id": "faq2",
       "group": {
            "id": "software"
       }
   }
]

I want to get this JSON data as result but I really couldn't have success on this. 我想获得此JSON数据,但我真的无法成功。 So how should I need to edit my "PHP webservice" to get this json result? 因此,我应该如何编辑我的“ PHP Webservice”以获取此json结果?

$faq = array();
while($row = mysql_fetch_assoc($query)) {
   $faq[] = array(
      'id' => $row['id'],
      'group' => array(
         'id' => $row['group']
       )
   );
}

首先执行以下操作:

$row['group'] = Array('id' => $row['group']);

Construct array like this 像这样构造数组

$arr = array();
$id = 0;
while($row = mysql_fetch_assoc($query)) {
    $arr[$i]['id'] = $row['id'];
    $arr[$i]['group']['id'] = $row['group'];
    $i++;
}

$json = json_encode($arr);

try this : 尝试这个 :

$arrayJson["id"] = $row["id"];
$arrayJson["group"]["id"] = $row["group"];
echo json_encode($arrayJson)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM