php讀取數(shù)據(jù)庫轉(zhuǎn)json數(shù)據(jù)的實現(xiàn)方法:首先連接數(shù)據(jù)庫并讀取數(shù)據(jù)庫;然后在數(shù)據(jù)庫讀取后,直接將數(shù)據(jù)轉(zhuǎn)換為數(shù)組顯示;最后通過“json_encode”轉(zhuǎn)為JSON即可。推薦:《PHP視頻教程》PHP讀取數(shù)據(jù)庫記錄轉(zhuǎn)換為JSON的代碼(API接口的SQL語句)為了提供API接口,我們常常在讀取數(shù)據(jù)庫后,將數(shù)據(jù)轉(zhuǎn)換為數(shù)組,通過json_encode轉(zhuǎn)為JSON,即可滿足使用需要?,F(xiàn)將代碼粘帖如下:讀取
php讀取數(shù)據(jù)庫轉(zhuǎn)json數(shù)據(jù)的實現(xiàn)方法:首先連接數(shù)據(jù)庫并讀取數(shù)據(jù)庫;然后在數(shù)據(jù)庫讀取后,直接將數(shù)據(jù)轉(zhuǎn)換為數(shù)組顯示;最后通過“json_encode”轉(zhuǎn)為JSON即可。
推薦:《PHP視頻教程》
PHP讀取數(shù)據(jù)庫記錄轉(zhuǎn)換為JSON的代碼(API接口的SQL語句)
為了提供API接口,我們常常在讀取數(shù)據(jù)庫后,將數(shù)據(jù)轉(zhuǎn)換為數(shù)組,通過json_encode轉(zhuǎn)為JSON,即可滿足使用需要?,F(xiàn)將代碼粘帖如下:
讀取一條記錄,轉(zhuǎn)為數(shù)組并輸出JSON
1 2 3 4 5 6 7 8 9 10 | 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條記錄,轉(zhuǎn)為多維數(shù)組并輸出JSON(第一種寫法)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $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條記錄,轉(zhuǎn)為多維數(shù)組并輸出JSON(第二種寫法)
1 2 3 4 5 6 7 8 | $sql = "select salesid,fromstore,fromsaler,salestime,salenum,totalprice from midea_sales" ;
$results = mysqli_query( $con , $sql );
while ( $rows = mysqli_fetch_assoc( $results )) {
$res [] = $rows ;
}
print_r( $res );
|
4.讀取N條記錄,轉(zhuǎn)為多維數(shù)組并輸出JSON(第三種寫法),適合獲取全部記錄
1 2 3 4 | $sql = "select salesid,fromstore,fromsaler,salestime,salenum,totalprice from midea_sales" ;
$results = mysqli_query( $con , $sql );
$rows = mysqli_fetch_all( $results );
print_r( $rows );
|
在轉(zhuǎn)換的過程中,JSON格式會出現(xiàn)[]和{}兩種格式的JSON,而實際應(yīng)用中對{}的接口是標(biāo)準(zhǔn)接口。如何轉(zhuǎn)換呢?
原因在于:當(dāng)array是一個從0開始的連續(xù)數(shù)組時,json_encode出來的結(jié)果是一個由[]括起來的字符串;而當(dāng)array是不從0開始或者不連續(xù)的數(shù)組時,json_encode出來的結(jié)果是一個由{}括起來的key-value模式的字符串。
1 2 3 4 5 6 | $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 );
|
以上就是php如何讀取數(shù)據(jù)庫轉(zhuǎn)json數(shù)據(jù)的詳細(xì)內(nèi)容,
https://www.php.cn/php-ask-457793.html