dongzhuo3376 2011-11-07 22:15
浏览 39
已采纳

将多维php数组分配给javascript数组

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'].";
";
print "var 25[".$i."]=" .$result1['25'].";
";
print "var 50[".$i."]=" .$result1['50'].";
";
print "var 100[".$i."]=" .$result1['100'].";
";
print "var 250[".$i."]=" .$result1['250'].";
";
print "var 500[".$i."]=" .$result1['500'].";
";
print "var plus[".$i."]=" .$result1['plus'].";
";
$i = $i+1;
}
print "var tick='1';
";
print "alert (tick);
";
print "</script>
";
?>
<script>
alert (500[0]);

</script>

This alerts undefined for the tick alert and nothing for the second alert.. Thanks..

  • 写回答

5条回答 默认 最新

  • dslfq06464 2011-11-07 22:18
    关注

    You cannot use an integer as a variable name, like in this line: print "var 25[".$i."]=" .$result1['25']."; ";. 25 cannot be a variable.

    If you want to map an array to a javascript object, you might want to take a look at json_encode

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题