为了提供API接口,我们常常在读取数据库后,将数据转换为数组,通过json_encode转为JSON,即可满足使用需要。现将代码粘帖如下:
- 读取一条记录,转为数组并输出JSON
include("../../db/conn.php");//数据库连接;
echo "<pre>";
//数据库读取后,直接转换为数组显示;
$sql = "select salesid,fromstore,fromsaler,salestime,salenum,totalprice from midea_sales WHERE salesid=44";
$results = mysqli_query($con, $sql);
$rows = mysqli_fetch_assoc($results);
foreach ($rows as $key => $v) {
$res[$key] = $v;
}
echo json_encode($res);
- 读取N条记录,转为多维数组并输出JSON(第一种写法)
//数据库读取后,直接转换为数组显示;
$sql = "select salesid,fromstore,fromsaler,salestime,salenum,totalprice from midea_sales";
$results = mysqli_query($con, $sql);
$data = array();//初始化数组;
class Alteration
{
public $fromstore;
public $fromsaler;
public $salenum;
public $totalprice;
}
while ($row = mysqli_fetch_assoc($results)) {
$alter = new Alteration();//实例化对象;
$alter->fromstore = $row['fromstore'];
$alter->fromsaler = $row['fromsaler'];
$alter->salenum = $row['salenum'];
$alter->totalprice = $row['totalprice'];
$data[] = $alter;
}
echo json_encode($data);
- 读取N条记录,转为多维数组并输出JSON(第二种写法)
$sql = "select salesid,fromstore,fromsaler,salestime,salenum,totalprice from midea_sales";
$results = mysqli_query($con, $sql);
while ($rows = mysqli_fetch_assoc($results)) {
$res[] = $rows;
}
//$res = str_replace('[', '{', json_encode($res));
//$res = str_replace(']', '}', $res);
print_r($res);
4.读取N条记录,转为多维数组并输出JSON(第三种写法),适合获取全部记录
$sql = "select salesid,fromstore,fromsaler,salestime,salenum,totalprice from midea_sales";
$results = mysqli_query($con, $sql);
$rows = mysqli_fetch_all($results);
print_r($rows);
在转换的过程中,JSON格式会出现[]和{}两种格式的JSON,而实际应用中对{}的接口是标准接口。如何转换呢?
原因在于:当array是一个从0开始的连续数组时,json_encode出来的结果是一个由[]括起来的字符串;而当array是不从0开始或者不连续的数组时,json_encode出来的结果是一个由{}括起来的key-value模式的字符串。
$sql = "select salesid,fromstore,fromsaler,salestime,salenum,totalprice from midea_sales";
$results = mysqli_query($con, $sql);
$rows = mysqli_fetch_all($results);
$rows = str_replace('[', '{', json_encode($rows));
$rows = str_replace(']', '}', $rows);
echo json_encode($rows);
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!