php将数据库查询结果返回为Json格式

<?php
  // 配置json 
  header("Content-type: application/json;charset=UTF-8");
  // 跨域配置
  header("Access-Control-Allow-Credentials: true");
  header("Access-Control-Allow-Origin: *");

  $conn = mysqli_connect('localhost','root','123456','my_test');	
  mysqli_query($conn,"set character set 'utf8'");
  mysqli_query($conn,"set names 'utf8'");
	$result=mysqli_query($conn,"select * from goodslist");
  $jarr = array();
	while ($rows=mysqli_fetch_array($result)){
	    $count=count($rows);//不能在循环语句中,由于每次删除 row数组长度都减小  
	    for($i=0;$i<$count;$i++){  
          unset($rows[$i]);//删除冗余数据
	    }
	    array_push($jarr,$rows);
	}
  
  $json = JSON_encode($jarr,JSON_UNESCAPED_UNICODE);
  $arr = json_decode($json);
  echo $json;
  // echo $arr;
	// echo $str=json_encode($jarr);//将数组进行json编码
?>

参考:

posted @ 2020-12-09 21:24  公瑾当年  阅读(931)  评论(0编辑  收藏  举报