PHP中把資料庫查詢結果輸出為json格式簡單一實例_php執行個體

來源:互聯網
上載者:User

include/conn.php為資料庫連結檔案,不會的網上搜尋

<?php include './include/conn.php'; //資料庫連結檔案$sql_notice = mysql_query('SELECT * FROM gg_notice where enable = "1" limit 0,10');$notice = mysql_fetch_array($sql_notice, MYSQL_ASSOC);print_r ($notice);?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>第一php網提供的教程--將資料庫讀取的資料產生json格式</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"/></script> --><script language=javascript></script></head><body><pre><h1>請注意兩種方法產生的對象數組在結構上的區別</h1><?phpecho '<h1>法一</h1>';//假設以下數組是根據我們從資料庫讀取的資料產生的$jarr=array('total'=>239,'row'=>array(      array('code'=>'001','name'=>'中國','addr'=>'Address 11','col4'=>'col4 data'),      array('code'=>'002','name'=>'Name 2','addr'=>'Address 12','col4'=>'col4 data'),                   )      );//法一:$jobj=new stdclass();//執行個體化stdclass,這是php內建的空類,可以用來傳遞資料,由於json_decode後的資料是以對象數組的形式存放的,//所以我們產生的時候也要把資料存放區在對象中foreach($jarr as $key=>$value){$jobj->$key=$value;}print_r($jobj);//列印傳遞屬性後的對象echo '使用$jobj->row[0][\'code\']輸出數組元素:'.$jobj->row[0]['code'].'<br>';echo '編碼後的json字串:'.json_encode($jobj).'<br>';//列印編碼後的json字串echo '<hr>';//法二:echo '<h1>法二</h1>';echo '編碼後的json字串:';echo $str=json_encode($jarr);//將數組進行json編碼echo '<br>';$arr=json_decode($str);//再進行json解碼print_r($arr);//列印解碼後的數組,資料存放區在對象數組中echo '使用$arr->row[0]->code輸出數組元素:'.$arr->row[0]->code;?> </body></html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.