分配多维PHP数组的JavaScript阵列 [英] assigning multidimensional php array to javascript array
问题描述
我知道这可能是重复的,但我不能环绕其他的例子我的大脑。帮助将AP preciated。
我有一个PHP数组,我需要分配到一个JavaScript数组。这是我做,现在的业余方式。
你可以看到在 http源://www.$p$pferweb.com/accentps/index。 PHP
I know this may be a duplicate, but I cant wrap my brain around the other examples. Help would be appreciated. I have a php array that i need to assign to a javascript array. Here is my amateur way of doing it now. You can see source at http://www.preferweb.com/accentps/index.php
<?php
$i=0;
while ($result1 = mysql_fetch_array($query1)){
print "<script>";
print "var size[".$i."]=" .$result1['type'].";\n";
print "var 25[".$i."]=" .$result1['25'].";\n";
print "var 50[".$i."]=" .$result1['50'].";\n";
print "var 100[".$i."]=" .$result1['100'].";\n";
print "var 250[".$i."]=" .$result1['250'].";\n";
print "var 500[".$i."]=" .$result1['500'].";\n";
print "var plus[".$i."]=" .$result1['plus'].";\n";
$i = $i+1;
}
print "var tick='1';\n";
print "alert (tick);\n";
print "</script>\n";
?>
<script>
alert (500[0]);
</script>
这提醒未定义蜱警报并没有什么第二警报..谢谢..
This alerts undefined for the tick alert and nothing for the second alert.. Thanks..
推荐答案
您不能在此行中使用一个整数作为变量名,如:[。$ I] 打印VAR 25 =$ RESULT1 ['25']。\\ n;
。 25不能是变量
You cannot use an integer as a variable name, like in this line: print "var 25[".$i."]=" .$result1['25'].";\n";
. 25 cannot be a variable.
如果要映射一个数组为JavaScript对象,你可能想看看的 json_en code
If you want to map an array to a javascript object, you might want to take a look at json_encode
示例结果
您code可以这样写:
EXAMPLE
Your code could be written like this:
<?php
$result = array();
while ($row = mysql_fetch_array($query1)){
$result[] = $row;
}
?>
<script>
var result = <?= json_encode($result); ?>;
alert (result[1][500]);
</script>
看起来清爽多了我。
looks much cleaner to me.
这篇关于分配多维PHP数组的JavaScript阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!