我们如何在php的帮助下从mysql数据库中分配一个javascript数组?

问题描述:

I would like to know if we can select data from the database using php and assign it to a javascript array? if so what would be the syntax?

I wrote the code below but it is not working

$js_array = "[";
$result = mysql_query("SELECT item_name FROM tbl_item");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
    $js_array .= $row[0]; 
    $js_array .= ",";
}
$js_array{ strlen($js_array)-1 } = ']';

 ?>

<script>
var cities = <?php echo  $js_array; ?>
for(var i=0; i<4;i++)
alert(cities.length);

</script> 

我想知道我们是否可以使用php从数据库中选择数据并将其分配给javascript数组? 那么语法是什么? p>

我编写了下面的代码,但它无法正常工作 p>

  $ js_array =“[”  ; 
 $ result = mysql_query(“SELECT item_name FROM tbl_item”); 
while($ row = mysql_fetch_array($ result,MYSQL_NUM)){
 $ js_array。= $ row [0];  
 $ js_array。=“,”; 
} 
 $ js_array {strlen($ js_array)-1} =']'; 
 
?&gt; 
 
&lt; script&gt; 
var cities =&lt  ;?php echo $ js_array;  ?&gt; 
for(var i = 0; i&lt; 4; i ++)
alert(cities.length); 
 
&lt; / script&gt;  
  code>  pre> 
  div>

The simplest approach is converting to JSON with json_encode:

// with $js_array being a true array
var cities = <?php echo json_encode($js_array)?>;

Note, that there are esoteric cases, where this solution might not work. On the other hand, the advantage is, that json_encode takes over all quoting needs.

You should not echo the array object.

Iterate the array and echo the value.

<?php foreach( $js_array as $value) echo "'$value',"; ?>