douba2705 2016-12-12 17:55
浏览 59

如何将PHP'while循环'插入JavaScript代码?

I need to display the values of an SQL table in a D3 map for each US state. Below is code excerpts from my file.php:

  1. Here is the SQL query:

    $sql = "SELECT COUNT(State) FROM `mytable`";
    $sql_result= mysqli_query($cnx,$sql) or die('Could not execute' . mysqli_error()) ;
    
  2. Here is how I pass the result into an array

     <? while($myvar=mysqli_fetch_array($sql_result)) { **need to add both php and javascript below..**  }
    
    <?php $js_array = json_encode($myvar['0']);?>
    
  3. Here is where I need to pass the data:

    .forEach(function(d){ 
        var     kpi01=<?php echo "var nbcustomers = ". $js_array . ";
    ";?>, //  No of customers in that state
                kpi02= .....
    
                sampleData[d]={kpi01, kpi02}; 
        });
    

Can anyone help me with suggestions to properly insert the JavaScript code after the while loop within the .forEach?

  • 写回答

1条回答 默认 最新

  • donglian1384 2016-12-14 19:09
    关注

    Don't mess around with trying to generate a bunch of variables with numbers in their names.

    Just construct the data structure you need (an array of your SQL query results) in PHP, then use json_encode to convert it to JavaScript.

     <?php
         $my_array = [];
         while($myvar=mysqli_fetch_array($sql_result)) {
             $my_array[] = $myvar;
         }
         $js_array = json_encode($my_array);
     ?>
     <script>
     var javascript_array = <?php echo $js_array; ?>;
     </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂