将PHP数组传递给Javascript变量

时间:2016-03-22 06:06:11

标签: javascript php arrays

php文件

$querySelectWordFilter = "SELECT * FROM badwordfilter";
      $stmtSelectWordFilter = $conn->prepare($querySelectWordFilter);
      $stmtSelectWordFilter->execute();
      while($rowSelectWordFilter = $stmtSelectWordFilter->fetch()){
         $Array[] = $rowSelectWordFilter["filterWord"];
      }

    foreach($Array as $val){
         echo $val;
    }

Javascript文件

<script>
 var filter = ['ass', 'evil','ugly'];
</script>

问题:首先,我从数据库中选择所有值并将其存储到数组中。但我如何将PHP数组变量传递给JavaScript过滤变量?

1 个答案:

答案 0 :(得分:9)

不需要foreach循环就可以创建你的数组

<script>
var filter = <?php echo json_encode($Array); ?>;
</script>

在JavaScript中使用List<MyObject> secondList = firstList;作为

$m_id = [];
DB::table("messages")
->where('processed','0')   
->chunk(100, function ($messages) use(&$m_id){
                foreach ($messages as $message) {
                    $m_id[] = $message->id;
                }
            });

echo "<pre>"; print_r($m_id); die;