PHP中把数据库查询结果输出为json格式

<?php  
header("Content-type:text/html;charset=utf-8");//字符编码设置  
$servername = "localhost";  
$username = "root";  
$password = "root";  
$dbname = "tjks";  

// 创建连接  
$con =mysqli_connect($servername, $username, $password, $dbname);  

// 检测连接  

  
$sql = "SELECT * FROM brands";  
$result = mysqli_query($con,$sql);  
if (!$result) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

$jarr = array();
while ($rows=mysqli_fetch_array($result,MYSQL_ASSOC)){
    $count=count($rows);//不能在循环语句中,由于每次删除 row数组长度都减小  
    for($i=0;$i<$count;$i++){  
        unset($rows[$i]);//删除冗余数据  
    }
    array_push($jarr,$rows);
}
print_r($jarr);//查看数组
echo "<br/>";
 
echo '<hr>';

echo '编码后的json字符串:';
echo $str=json_encode($jarr);//将数组进行json编码
echo '<br>';
$arr=json_decode($str);//再进行json解码
echo '解码后的数组:';
print_r($arr);//打印解码后的数组,数据存储在对象数组中
mysqli_close($con);
?> 

输出内容如下:

Array ( [id] => 1 [name] => GNC ) Array ( [id] => 2 [name] => TCBJ ) Array ( [id] => 3 [name] => TJKS )
Unicode编码后的json数据: [{"id":"1","name":"GNC"},{"id":"2","name":"TCBJ"},{"id":"3","name":"TJKS"}] 

可以看到,直接进行json_encode();编码,是将三个数组分别转为了json格式,而且两端会出现中括号!!还有另外一种写法

<?php  
header("Content-type:text/html;charset=utf-8");//字符编码设置  
$servername = "localhost";  
$username = "root";  
$password = "root";  
$dbname = "tjks";  

// 创建连接  
$con =mysqli_connect($servername, $username, $password, $dbname);  

// 检测连接  

  
$sql = "SELECT * FROM brands";  
$result = mysqli_query($con,$sql);  
if (!$result) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

$jarr = array();
while ($rows=mysqli_fetch_array($result,MYSQL_ASSOC)){
    $count=count($rows);//不能在循环语句中,由于每次删除 row数组长度都减小  
    for($i=0;$i<$count;$i++){  
        unset($rows[$i]);//删除冗余数据  
    }
    array_push($jarr,$rows);
}
print_r($jarr);//查看数组
echo "<br/>";
echo '<hr>';

$jobj=new stdclass();//实例化stdclass,这是php内置的空类,可以用来传递数据,由于json_encode后的数据是以对象数组的形式存放的,
//所以我们生成的时候也要把数据存储在对象中
foreach($jarr as $key=>$value){
$jobj->$key=$value;
}
echo '传递属性后的对象:';
print_r($jobj);//打印传递属性后的对象
echo '<br>';
echo '编码后的json字符串:'.json_encode($jobj).'<br>';//打印编码后的json字符串
mysqli_close($con);
?> 

输出内容如下:

Array ( [0] => Array ( [id] => 1 [name] => GNC ) [1] => Array ( [id] => 2 [name] => TCBJ ) [2] => Array ( [id] => 3 [name] => TJKS ) )
传递属性后的对象:stdClass Object ( [0] => Array ( [id] => 1 [name] => GNC ) [1] => Array ( [id] => 2 [name] => TCBJ ) [2] => Array ( [id] => 3 [name] => TJKS ) )
编码后的json字符串:{"0":{"id":"1","name":"GNC"},"1":{"id":"2","name":"TCBJ"},"2":{"id":"3","name":"TJKS"}}

这样一来,中括号没有了,数组也成为了有序的数组!

posted @ 2017-03-02 15:55  Yiven  阅读(32386)  评论(1编辑  收藏