php json_encode實現與中文亂碼解決方案

來源:互聯網
上載者:User

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);

//結果

//{"a":1,"b":2,"c":3,"d":4,"e":5}

/*

下面看一款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--;
}


 
/**************************************************************
 *
 * 將數群組轉換為json字串(相容中文)
 * @param array $array  要轉換的數組
 * @return string  轉換得到的json字串
 * @access public
 *
 *************************************************************/

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).'})';

 

聯繫我們

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