為什麼下面這句話沒有輸出任何東西?
echo json_encode($result);#輸出結果
個人覺得可能是因為$data裡面的數組元素為Client對象,在轉為json的時候出問題了。但是我不知道是什麼問題,怎麼轉換?或者有沒有其他的轉換方法?
class Result {var $state;var $data = array();}
完整代碼:
$start = 0;$end = 2;$uid = 1;$result = new Result();$result_set = getClients($start, $end, $uid);$data = array();$count = 0;while($row = mysql_fetch_array($result_set)) {$client = new Client();$client->cid = $row['id'];$client->gender = $row['gender'];$client->rank = $row['rank'];$client->name = $row['name'];$client->phoneNum = $row['phoneNum'];$client->email = $row['email'];$client->address = $row['address'];$result->data[$count] = $client;echo $result->data[$count]->cid." ";echo $result->data[$count]->gender." ";echo $result->data[$count]->rank." ";echo $result->data[$count]->name." ";echo $result->data[$count]->phoneNum." ";echo $result->data[$count]->address."\n";$count++; }if(count($data) > 0) {$result->state = 0;} else {$result->state = 1;}echo json_encode($result);#輸出結果class Result {var $state;var $data = array();}
輸出結果:
---------- debug php ----------Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in D:\WWW\wsd\trunk\src\server\api\db\init_db.php on line 10Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in D:\WWW\wsd\trunk\src\server\api\db\init_db.php on line 103 0 經理 張小莉 18825044888 廣東省廣州市天河區4 0 主管 吳美鳳 18576430777 廣東省深圳市南山區蛇口南海大道1079號PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in D:\WWW\wsd\trunk\src\server\api\db\init_db.php on line 10PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in D:\WWW\wsd\trunk\src\server\api\db\init_db.php on line 10Output completed (0 sec consumed) - Normal Termination
應該有輸出類似這種格式才對的:
{"state":1,"data":[ {"cid":3, "gender":0, "rank":"經理" "name":" 張小莉" "phoneNum":"18825044888 " "address":"廣東省廣州市天河區"}, {"cid":4, "gender":0, "rank":"主管" "name":" 吳美鳳" "phoneNum":"18576430777 " "address":" 廣東省深圳市南山區蛇口南海大道1079號"} ]}
請問這是什麼問題呢?怎麼解決?謝謝!
回複討論(解決方案)
print_r($result);
能看到什嗎?
$result是一個對象來的,輸出有錯:
Catchable fatal error: Object of class Result could not be converted to string in D:\WWW\wsd\trunk\src\server\api\getClients.php on line 44
Object of class Result could not be converted to string 對象不能被轉換為字串
既如此,當然也不能 json 了
看看你的 Client 類定義
可能沒有值吧
編碼問題,json_encode()只對utf-8有效,建立資料庫表的時候設定好表的編碼為utf-8,串連資料庫的時候也設定一下編碼就行了,類似:
function connect_host() {
$host = "127.0.0.1";
$name_db = "root";
$password_db ="root";
$name_tb = "wsd_db";
$con = mysql_connect($host, $name_db, $password_db);
if(!$con) {
echo "connect host failed". mysql_error();
return;
}
mysql_select_db($name_tb, $con);
mysql_query("SET NAMES UTF8");#設定utf-8編碼
return $con;
}