Home  >  Article  >  php教程  >  PHP数组传递给JavaScript以及json_encode的gbk中文乱码的解决 - jerrylsxu

PHP数组传递给JavaScript以及json_encode的gbk中文乱码的解决 - jerrylsxu

WBOY
WBOYOriginal
2016-05-20 10:19:211138browse

首先关于json_encode的gbk中文乱码,创建JSON函数,这一段来自网上某一位大侠

复制代码
/**************************************************************
 *
*    使用特定function对数组中所有元素做处理
*    @param    string    &$array        要处理的字符串
*    @param    string    $function    要执行的函数
*    @return boolean    $apply_to_keys_also        是否也应用到key上
*    @access public
*
*************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
    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]);
            }
        }
    }
}

/**************************************************************
 *
*    将数组转换为JSON字符串(兼容中文)
*    @param    array    $array        要转换的数组
*    @return string        转换得到的json字符串
*    @access public
*
*************************************************************/
function JSON($array) {
    arrayRecursive($array, 'urlencode', true);
    $json = json_encode($array);
    return urldecode($json);
}
复制代码

连接数据库取值给数组$array1

复制代码
$dbcnx = @mysql_connect ( "localhost", "root", "1234" );
if (! $dbcnx) {
    echo ("Unable to connect to the " . "database server at this time.");
    exit ();
}

if (! @mysql_select_db ( "pms" )) {
    echo ("Unable to locate the joke " . "database at this time.");
    exit ();
}

mysql_query ( "SET NAMES 'GB2312'" );

    $q=mysql_query("select * from ability where ALV = 1"); 
    while($row=mysql_fetch_array($q)){ 
     $array1[] = $row[AName];
}
复制代码

数组array1传递到JavaScript给数组ability1

复制代码

复制代码
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn