admin管理员组文章数量:1279083
I have a PHP array I want to use in my JavaScript code. I'd rather not do something like <?PHP $array['array2name'][0]?>
for all of the elements in it as it's number is unknown. I was going to do a while loop to write in some of the data into elements but I cannot seem to find an easy way to do this currently.
How do I pass a 2d array from PHP to JavaScript in the easiest way possible?
I have a PHP array I want to use in my JavaScript code. I'd rather not do something like <?PHP $array['array2name'][0]?>
for all of the elements in it as it's number is unknown. I was going to do a while loop to write in some of the data into elements but I cannot seem to find an easy way to do this currently.
How do I pass a 2d array from PHP to JavaScript in the easiest way possible?
Share Improve this question edited Apr 19, 2012 at 2:06 No Results Found 103k38 gold badges198 silver badges231 bronze badges asked May 12, 2010 at 9:41 133794m3r133794m3r 5,1183 gold badges25 silver badges37 bronze badges 2- 2 Lots of duplicates I can see in the right column. E.g. stackoverflow./questions/2421875/… (addresses the same issue) – Felix Kling Commented May 12, 2010 at 10:03
- possible duplicate of Best way to transfer an array between PHP and Javascript – No Results Found Commented Apr 19, 2012 at 2:06
2 Answers
Reset to default 12As a JSON Object using the json_encode function. You can then read this with Javascript easily as it is a native javascript object. http://php/manual/en/function.json-encode.php
json_encode($array);
JSON is easily parsable in JQuery, but for pure JavaScript see here:
http://www.json/js.html
Lazy method:
<script>
var arr = [];
<?php
$phparray = array(array(1, 2, 3), array(4, 5, 6));
foreach ($phparray as $i) {
echo 'arr.push([' . implode(', ', $i) . ']);';
}
?>
</script>
This isn't the "best" method, but hey it works.
本文标签: Best way to pass a 2d array into JavaScript from PHPStack Overflow
版权声明:本文标题:Best way to pass a 2d array into JavaScript from PHP? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741257126a2366893.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论