Home > php教程 > php手册 > php 二维数组传递给 js 问题解决记录

php 二维数组传递给 js 问题解决记录

WBOY
Release: 2016-06-13 09:24:23
Original
1463 people have browsed it

php 二维数组传递给 js 问题解决记录

需求:

php从数据库中读取到二维数组,传递到js中


实现步骤:

php:json_encode → json → js:eval

即在php中使用json_encode()将php的二维数组转化成json格式,传递到js中,使用eval()解析得到js的二维数组。


代码:

php:

<?php  
header("Content-Type: text/html; charset=utf8") ;
$con=mysqli_connect("url","name","password","databasename");
// Check connection
if (mysqli_connect_errno($con))
    echo "Failed to connect to MySQL: " . mysqli_connect_error();

mysqli_query($con,"set character set &#39;utf8&#39;");
mysqli_query($con,"set names &#39;utf8&#39;");

$json_arr = array(array("a","b","c",1,2,3),array("q","w",1,2));
$jsonstr = json_encode($json_arr);

?>
var json=<?=$jsonstr?>;
Copy after login

Copy after login
js:

<script type="text/javascript" src="http://.../test.php"></script>
<script language="javascript" type="text/javascript">	    
	$(document).ready(function(){
	    var jsonstr =eval(json);
	    for(var k=0;k<jsonstr.length;k++){
               for(var i=0;i<jsonstr[k].length;i++)
                  alert(jsonstr[k][i]);
            }
        })
</script>
Copy after login

遇到的问题:

1.php中二维数组使用json_encode()转化成json时,第二维数组可以echo出来,但是转化成json为空。

到网上查资料确定问题是第二维数组中含有非utf8编码。果然,我把二维数组中第二维数组互换位置,变成第一个数组的json为空了。

结论:json_encode()可以转化多维数组,但是基本要求是编码为utf8。遇到多维数组中某一子数组转化json为null,极有可能使这一子数组中含有编码不是utf8的元素。


2.wamp mysql 在phpmyadmin中看到数据表内容是正常汉字,但是用php读取出来打印发现汉字都变成?了。

数据库中各个表的整理方式都是utf8_general_ci,php文件中也声明了

header("Content-Type: text/html; charset=utf-8") ;
...
mysqli_query($con,"set character set &#39;utf-8&#39;");
mysqli_query($con,"set names &#39;utf-8&#39;");
Copy after login
这些代码我一直是这么用的(之前用的是wamp低版本,还是用的mysql_query,现在报错说废弃了,就改成了mysqli),之前也没出现过中文变成?的情况。网上一查,原来是utf-8与utf8这个地方。。。

应该是这样:

header("Content-Type: text/html; charset=utf8") ;
...
mysqli_query($con,"set character set &#39;utf8&#39;");
mysqli_query($con,"set names &#39;utf8&#39;");
Copy after login
结论:mysql中还是使用utf8吧。。。无语。



Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template