在PHP编码和解码问题

时间:2018-03-14 10:32:48

标签: javascript php google-maps

我正在使用php,我需要将数组转换为javascript数组。如何更改? 请帮助下面是我的输出值。

我正在尝试从长时间调试但没有获得任何线索。

我的PHP代码:

<?php
  include "db_connection.php";
  $locations=array();
      $query =  $conn->query('SELECT `pg_address` FROM `tbl_master_property` limit 10');
       while ($row = $query->fetch_assoc()) {
         $locations[] = $row;
      }
      $locations = json_encode($locations);
      //echo "<pre>";print_r($locations);die;
?>

数组php值输出:

Array
(
    [0] => Array
        (
            [pg_address] =>  # 3/20, 1st Main, 1st Cross, Hosur Main Road, Adugodi, Bangalore
        )

    [1] => Array
        (
            [pg_address] =>  24/3 Bazaar Street, Adugodi, Bangalore - 560030
        )

    [2] => Array
        (
            [pg_address] => # 430, Koramangala 7th Block, Beside Sai Baba Temple, Bangalore
        )

    [3] => Array
        (
            [pg_address] => # 41, 1st Cross, 2nd Main, Behind M R Granite, Adugodi, Bannerghatta Main Road, Bangalore
        )

    [4] => Array
        (
            [pg_address] =>  # 27, 2nd Main, B cross, Nanjappa Layout, Adugodi, opp. to Vijaya Bank, Bangalore
        )

)

Javascript代码:

var locations = <?= $locations ?>;

// ---我需要在js ---- //

中使用这样的格式
var locations = [
           '3/20, 1st Main, 1st Cross, Hosur Main Road, Adugodi, Bangalore',
           '24/3 Bazaar Street, Adugodi, Bangalore - 560030',
           '# 430, Koramangala 7th Block, Beside Sai Baba Temple, Bangalore',
           '# 41, 1st Cross, 2nd Main, Behind M R Granite, Adugodi, Bannerghatta Main Road, Bangalore',
           '# 27, 2nd Main, B cross, Nanjappa Layout, Adugodi, opp. to Vijaya Bank, Bangalore'  
  ];

3 个答案:

答案 0 :(得分:0)

在你的php while循环更改下面的行。

$locations[] = $row['pg_address'];

尝试检查它是否有效?你的问题也不是很清楚,但这可能对你有帮助。

答案 1 :(得分:0)

此代码可能适合您:

array_push($locations,json_encode($row['pg_address']));

答案 2 :(得分:0)

使用json_encode PHP函数对数据进行编码并分配到Javascript变量中,该变量将为您提供所需的输出数组,您的更新代码将如下所示

<?php
  include "db_connection.php";
  $locations=array();
      $query =  $conn->query('SELECT `pg_address` FROM `tbl_master_property` limit 10');
       while ($row = $query->fetch_assoc()) {
         $locations[] = $row['pg_address'];
      }
?>

在javascript中,

var locations = <?php echo json_encode($locations) ?>;

希望这有帮助。