php文件到php数组到js数组 - 作为数组的数组

时间:2014-09-05 22:12:05

标签: javascript php arrays mysqli

...
$php_array = mysqli_fetch_all($result,MYSQLI_ASSOC);
?>

<script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var location = ". $js_array . ";\n";
?>
</script>   

如何修改上面给我这个输出的代码(一个对象数组?)

var javascript_array = [
    {"city":"Hermosa Beach","lat":"33.860069","lng":"-118.398784"},
    {"city":"San Jose","lat":"34.694628","lng":"-118.398784"},
    .... ]

给我这个......(数组数组?)

var javascript_array = [
    ["Hermosa Beach",33.860069,-118.398784],
    ["San Jose",34.694628",-118.398784],
    .... ]  

没有一堆预告......

2 个答案:

答案 0 :(得分:2)

致电MYSQLI_NUM时,请使用MYSQL_ASSOC代替mysqli_fetch_all()。然后行将是索引数组而不是关联数组。

虽然我不知道为什么你希望这个数组是这样的。数组应该用于统一数据,对象应该用于异构数据。

答案 1 :(得分:1)

谢谢,这很有效,非常精益......

<?php

    $query = "SELECT * FROM file";
    $result = $con->query($query);

    // Fetch all rows and return the result-set as an associative array:
    // using numeric keys for the array, instead of creating an associative array.
    $php_array = mysqli_fetch_all($result,MYSQLI_NUM);
?>  

<script type='text/javascript'>
    <?php

    // create a JSON representation of a value that javascript will understand
    $js_array = json_encode($php_array);

    // dump json object into javascript variable 'locations'
    echo "var locations =" .  $js_array . ";\n";
    ?>
</script>