Php Multidimensional数组对象为Javascript Json

时间:2022-11-12 21:31:06

I've got a multidemnsional array as an object in PHP and like to print it in Javascript. This is as for I've reached.

我有一个多维数组作为PHP中的对象,并喜欢在Javascript中打印它。这是我达成的。

PHP:

PHP:

$words = $wordlist->getWordlist($var1,$var2);

Now i usually printed the array like this in PHP:

现在我通常在PHP中打印这样的数组:

foreach ($words as $section => $items)
    foreach ($items as $key => $value)
        echo "$key\t = $value";

This is what I'm trying to do in Javascript:

这是我在Javascript中尝试做的事情:

var coders= <?php print json_encode($words); ?>;

for(var i = 0, l =coders.length; i < l; i++) {
    for(var j = 0, l2 = coders[i].length; j < l2; j++) {
        var value = coders[i][j];
        document.write(value);
    }
} 

This is my result when i print:

这是我打印时的结果:

document.write(coders);
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Thanks!

谢谢!

1 个解决方案

#1


2  

if you don't mind using jquery, you can use this:

如果你不介意使用jquery,你可以使用这个:

var json_obj = $.parseJSON(data);
$.each(json_obj , function(k, v) {  
    $.each(v, function(k2, v2) {
        alert("key is " +k2);
        alert("value is " +v2);         
    });
});

where data is your json string, like you would receive back from a PHP script echo json_encode($nested_array) ajax call

数据是你的json字符串,就像你从PHP脚本中收到的回复json_encode($ nested_array)ajax调用

#1


2  

if you don't mind using jquery, you can use this:

如果你不介意使用jquery,你可以使用这个:

var json_obj = $.parseJSON(data);
$.each(json_obj , function(k, v) {  
    $.each(v, function(k2, v2) {
        alert("key is " +k2);
        alert("value is " +v2);         
    });
});

where data is your json string, like you would receive back from a PHP script echo json_encode($nested_array) ajax call

数据是你的json字符串,就像你从PHP脚本中收到的回复json_encode($ nested_array)ajax调用