php mysql json文档化妆

时间:2016-05-09 12:36:14

标签: php mysql json

我正在使用这个代码来生成一个mysql表的json数据:

$sql = "select * from u3D15";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
    while($row=mysql_fetch_row($result)){
        $json['title'][]=$row;
    }
}
mysql_close($db_name);
echo json_encode($json); 

但这就是json的样子:{"title":[["1","kevin","t0E0GAA"]]}

我喜欢它:

{
   "title" : "Decode JSON",
   "ID" : 20,
   "buttons" :
   [
     {
       "title" : "kevin ",
       "image" : "t0E0GAA"
     },
     {
       "title" : "lora ",
       "image" : "v1AWYqR"
     }
   ]
}

如何更改文件的构成?

3 个答案:

答案 0 :(得分:1)

自己设置数组以获得格式化结果。

$json = array(); //create empty array
$json["title"] = "Decode JSON";
$json["ID"] = 20;
$json["buttons"] = array(); //empty nested array - we will fill it by MySQL results

$sql = "select * from u3D15";
$result = mysql_query($sql);
if(mysql_num_rows($result)){
    while($row=mysql_fetch_row($result)){
        $json["buttons"][]=$row; //insert mysql rows to buttons array
    }
}
mysql_close($db_name);
echo json_encode($json); 

答案 1 :(得分:1)

这很简单,只需像这样构建你的数组:

$json['title']='Decode JSON';
$json['ID']='20';
$json['buttons']['title']='kevin';
$json['buttons']['image']='t0E0GAA';

echo "<pre>";
echo json_encode($json); 

答案 2 :(得分:1)

尝试以下代码:

$sql = "select * from u3D15";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
    while($row=mysql_fetch_row($result)){
        $json['title']=$row[1];
        $json['ID']=$row[0];
        $json['buttons']['title']=$row[1];
        $json['buttons']['image']=$row[2];
    }
}
mysql_close($db_name);
echo json_encode($json); 

希望这能解决你的目的..