简体   繁体   English

PHP数组到JavaScript与json_encode更改数组

[英]php array to javascript with json_encode changes the array

I was looking for a way to convert a php array into a javascript array. 我在寻找一种将php数组转换为javascript数组的方法。

This was supposed to be done with json_encode as follows. 这应该使用json_encode如下完成。 Pass a PHP array to a JavaScript function 将PHP数组传递给JavaScript函数

I did this with my code but instead of giving me the original array items javascript only gave me the index numbers of the array and the data seems to be gone. 我用我的代码做到了这一点,但是javascript没有给我原始的数组项,而是给了我数组的索引号,并且数据似乎消失了。

Here is the PHP code. 这是PHP代码。

//creates array.
$ar = array("item 1","item2","etc");

foreach($ar as $item){
    echo $item;
}//prints the array items.(so item1 item2 etc)

Here is the javascript code. 这是JavaScript代码。

//Supposibly turns the php array into a js array.
var ar = <?php echo json_encode($ar); ?>;

for(var x in ar){
    alert(x);
}//alerts the indexes and not the array items.(so 0 1 2)

Did I miss something important here, since everywhere I search they said json_encode should work. 我是否错过了一些重要的事情,因为在我搜索的所有地方都说json_encode应该可以工作。 But for me it doesn't. 但是对我来说却不是。

I do know the arrays are connected because if I add an item to "$ar" then "var ar" also has an extra item. 我确实知道数组已连接,因为如果我将一个项目添加到“ $ ar”,那么“ var ar”也会有一个额外的项目。

The foreach syntax in JavaScript is not meant to be used for arrays, but for objects. JavaScript中的foreach语法并非用于数组,而是用于对象。

for (var key in obj)

gives you the keys of the object, not the respective values. 为您提供对象的键,而不是各个值。 In order to access those, you would have to use obj[key] . 为了访问这些,您必须使用obj[key] However, JavaScript arrays should rather be iterated over using a common for loop like this: 但是,应该使用如下通用的for循环来迭代JavaScript数组:

var length = arr.length;

for (var i = 0; i < length; i++) {
    // Do stuff with arr[i] here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM