| 
       php 中使用 json_encode() 内置函数(php > 5.2)可以使用得 php 中数据可以与其它语言很好的传递并且使用它,这个函数的功能是将数值转换成json数据存储格式. 
	
	- $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 
 
	- echo json_encode($arr); 
 
	-  
 
	-  
 
	 
 
下面看一款json_encode中文乱码问题: 
解决方法是用urlencode()函数处理以下,在json_encode之前,把所有数组内所有内容都用urlencode()处理一下,然用json_encode()转换成json字符串,最后再用urldecode()将编码过的中文转回来. 
	
	- 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--; 
 
	- } 
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	- function json($array) { 
 
	-  arrayrecursive($array, 'urlencode', true); 
 
	-  $json = json_encode($array); 
 
	-  return urldecode($json); 
 
	- } 
 
	- $array = array 
 
	-        ( 
 
	-           'name'=>'希亚', 
 
	-           'age'=>20 
 
	-        ); 
 
	- echo json($array); 
 
	 
 
应用实例: 
	
	- $servname="localhost"; 
 
	- $sqlservname="root"; 
 
	- $sqlservpws="123456"; 
 
	- $sqlname="lock1"; 
 
	- $db=mysql_connect($servname,$sqlservname,$sqlservpws) or die("数据库连接失败"); 
 
	- mysql_select_db($sqlname,$db); 
 
	- $sql = "select * from t_operater"; 
 
	- $result =mysql_query($sql); 
 
	- $rows = mysql_num_rows($result); 
 
	- while($obj = mysql_fetch_object($result)) 
 
	- { 
 
	- $arr[] = $obj; 
 
	- } 
 
	- echo '({"total":"'.$rows.'","results":'.json_encode($arr).'})'; 
 
	 
 
      
      (责任编辑:admin) |