php返回json資料函數例子

來源:互聯網
上載者:User

標籤:http   io   os   ar   for   檔案   資料   sp   c   

json_encode()函數用法。

echo json_encode(array(‘a‘=>‘bbbb‘,‘c‘=>‘ddddd‘);

這樣就會產生一個標準的json格式的資料

代碼如下 複製代碼
<?php

//需要執行的SQL語句
//單條
$sql="select id,name from tbl_user where id=1";
//多條資料
//$sql="select id,name from tbl_user";

//調用conn.php檔案進行資料庫操作
require(‘Conn.php‘);

//提示操作成功資訊,注意:$result存在於conn.php檔案中,被調用出來
if($result)
{

// $array=mysql_fetch_array($result,MYSQL_ASSOC);


/*資料集

$users=array();
$i=0;
while($row=mysql_fetch_array($result,MYSQL_ASSOC)){

echo $row[‘id‘].‘-----------‘.$row[‘name‘].‘</br>‘;
$users[$i]=$row;
$i++;

}
echo json_encode(array(‘dataList‘=>$users));

*/

/*單條資料*/

$row=mysql_fetch_row($result,MYSQL_ASSOC);

echo json_encode(array(‘jsonObj‘=>$row));
}

mysql_free_result($result);
//釋放結果
mysql_close();
//關閉串連

?>

上面是資料庫產生json資料了

單條資料:{"jsonObj":{"id":"1","name":"lmw"}}

多條資料:{"dataList":[{"id":"1","name":"lmw"},{"id":"2","name":"xxj"},{"id":"3","name":"xxxj"}]}


現在很多情況下,我們需要程式返回一個Json格式的結果,比如:

代碼如下 複製代碼
{
"UserKeyGetResponse":
{"RequestName":"e99e6d63e8c712d7699f52978a","api_key_value":"41954dd9b1cb6a95802eab6810"},
"error_response":
{"code":"NO_ERROR(www.111cn.net)","msg":"擷取系統參數成功"}
}

可以將結果寫成這樣的數組形式:
$respon = array(‘UserKeyGetResponse‘ => array(‘RequestName‘ => $api_request_name, ‘api_key_value‘ => $api_key_value),
‘error_response‘ => array(‘code‘ => ‘NO_ERROR‘, ‘msg‘ => ‘擷取系統參數成功‘));

代碼

代碼如下 複製代碼
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
static $recursive_counter = 0;
if (++$recursive_counter > 1000) {
die(‘possible deep recursion attack‘);
}
foreach ($array as $key => $value) {
if (is_array($value)) {
arrayRecursive($array[$key], $function, $apply_to_keys_also);
} else {
$array[$key] = $function($value);
}
if ($apply_to_keys_also && is_string($key)) {
$new_key = $function($key);
if ($new_key != $key) {
$array[$new_key] = $array[$key];
unset($array[$key]);
}
}
}
$recursive_counter--;
}

g:
$error_respon = array(‘code‘ => ‘ERROR_MSG_MISS‘, ‘msg‘ => ‘訊息不存在‘);
echo JSON($array);

結果為:
{"code":"ERROR_MSG_MISS","msg":"訊息不存在"}
用戶端就可以解析這個結果了,當然錯誤碼要用數字代替。

這樣就好多了我們顯示的直接是中文了,當然顯示那個16進位的編碼也是沒有問題的哦。
from:http://www.111cn.net/phper/php/62544.htm

php返回json資料函數例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.