php查询数据库返回json类型结果

php查询数据库返回json类型结果

<?php
$servername = "***.***.***.***";
$username = "***";
$password = "***";
$dbname = "******";
 
$json = '';
$data = array();
 
class Dustbin 
{
	public $id;
	public $name;
	public $title;
	public $content;
	public $longitude;
	public $latitude;
	public $point;
	public $isOpen;
	public $icon;
	public $ip;
	
	public $full_0;
	public $full_1;
	public $full_2;
	public $full_3;
}
 
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
} 
 
$sql = "SELECT id, baidu_lon,baidu_lat,full_0,full_1,full_2,full_3 FROM lese";
$result = $conn->query($sql);
 
if ($result->num_rows > 0) {
    // 输出数据
	$index=0;
    while($row = $result->fetch_assoc()) {
		$icon1=array("w"=>23,"h"=>25,"l"=>0,"t"=>21,"x"=>9,"lb"=>12);
		$icon2=array("w"=>23,"h"=>25,"l"=>46,"t"=>21,"x"=>9,"lb"=>12);
        $dustbin = new Dustbin();
		$dustbin->id=($index);
		$dustbin->name="dustbin".($index);
		$dustbin->title="dustbin".($index);
		$dustbin->content="notes".($index);
		$dustbin->ip = $row["id"];
		$dustbin->longitude=$row["baidu_lon"];
		$dustbin->latitude=$row["baidu_lat"];
		$dustbin->point="".($row["baidu_lon"])."|".($row["baidu_lat"]);
		$dustbin->isOpen=0;
		$dustbin->full_0 = $row["full_0"];
		$dustbin->full_1 = $row["full_1"];
		$dustbin->full_2 = $row["full_2"];
		$dustbin->full_3 = $row["full_3"];
		$flag = ($dustbin->full_0+$dustbin->full_1+$dustbin->full_2+$dustbin->full_3);
		if ($flag == 0){
			$dustbin->icon=$icon1;
		}
		else{
			$dustbin->icon=$icon2;
		}
		
		array_push($data,$dustbin);
		$index+=1;
    }
	$json = json_encode($data);//把数据转换为JSON数据.
	echo $json;
} else {
    echo $json;
}
$conn->close();
?>