admin管理员组文章数量:1346287
I have an array($my_array) that looks something like:
array(2) {
[25]=>int(10)
[30]=>int(8)
}
I'd like to assign it to a javascript array, but am having difficulties doing it. Any suggestions?
Edit: At first, I thought I could just assign it like a string, but that isn't working:
var photo_limit = $my_array;
I tried also doing a var_dump into my js value.
I'm currently trying to use something like:
for($i=0;$i<count($my_array); $i++){
echo "a[$i]='".$a[$i]."';\n";
}
Thanks.
I have an array($my_array) that looks something like:
array(2) {
[25]=>int(10)
[30]=>int(8)
}
I'd like to assign it to a javascript array, but am having difficulties doing it. Any suggestions?
Edit: At first, I thought I could just assign it like a string, but that isn't working:
var photo_limit = $my_array;
I tried also doing a var_dump into my js value.
I'm currently trying to use something like:
for($i=0;$i<count($my_array); $i++){
echo "a[$i]='".$a[$i]."';\n";
}
Thanks.
Share Improve this question edited Aug 12, 2011 at 13:33 etm124 asked Aug 12, 2011 at 13:27 etm124etm124 2,1404 gold badges41 silver badges78 bronze badges 2- how are you doing it now? when do you need to initiate it? – Kasia Gogolek Commented Aug 12, 2011 at 13:28
- 2 I would use json_encode to encode the object as JSON. JSON is perfect when working with JS. – Jay Commented Aug 12, 2011 at 13:29
2 Answers
Reset to default 10The best way is to use json_encode
. See json_encode reference
Used like this:
<script>
var array = <?php echo json_encode($array)?>;
</script>
Note, hovewer, that you'll receive Javascript object, instead of array. At a glance the only difference is if you have string keys in your array, you'll be able to access them in JS like array.*string key*
, i.e. using dot notation.
1: json_encode
your PHP array.
2: Decode the JSON string in JavaScript using eval
(alternative: jQuery.parseJSON)
<script>
var arr = eval('(<?php echo json_encode($thePhpArray); ?>)');
</script>
本文标签: Passing a multidimensional PHP array to javascriptStack Overflow
版权声明:本文标题:Passing a multidimensional PHP array to javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743824909a2545461.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论