将PHP数组转换为JavaScript对象

时间:2015-12-21 11:30:04

标签: javascript php arrays json

我在这里遇到麻烦了!由于我缺乏JSON和JS的知识,似乎有些不对劲。这是我的小代码:

$markersData = array();

$x = 0;
while ($row = @mysqli_fetch_assoc($result))
{
  $type = $row['type'];
  $markersData[$type][$x]['name'] = $row['name'];
  $markersData[$type][$x]['location_latitude'] = $row['location_latitude'];
  $markersData[$type][$x]['location_longitude'] = $row['location_longitude'];
  $markersData[$type][$x]['map_image_url'] = '';
  $markersData[$type][$x]['name_point'] = $row['name_point'];
  $markersData[$type][$x]['description_point'] = $row['description_point'];
  $markersData[$type][$x]['url_point'] = $global['rootURI'] . '/view.php?id=' . $row['id'];
  $x ++;
} 

我在检索行后直接将SQL数据存储在php数组中。现在,使用JSON方法,这是我的试用,但显然它没有加载或工作。

var
    mapObject,
    markers = [],
    markersData = JSON.parse( '<?php echo json_encode($markersData); ?>' );

我正在寻找转换后的php数组,以完成与此JS代码相同的工作:

 var
    mapObject,
    markers = [],
    markersData = {
            'Shop': [
            {
                name: 'Bondi Beach',
                location_latitude: 43.119445, 
                location_longitude: 131.881006,
                map_image_url: 'img/img.png',
                name_point: 'Vladivostok',
                description_point: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard',
                url_point: '02.html'
            }
            ],
            'Cinema': [
            {
                name: 'Bondi Beach',
                location_latitude: 43.124034, 
                location_longitude: 131.883517,
                map_image_url: 'img/img.png',
                name_point: 'Vladivostok',
                description_point: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard',
                url_point: '02.html'
            },
            {
                name: 'Coogee Beach',
                location_latitude: 43.126117, 
                location_longitude: 131.877423,
                map_image_url: 'img/img2.png',
                name_point: 'Matart Group',
                description_point: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard',
                url_point: '02.html'
            }
            ]
        };

我在这里做错了什么?

编辑:有些人让我向他们展示输出。它可以在这里找到:http://pastebin.com/7Ebz2GzP

2 个答案:

答案 0 :(得分:0)

您应该使用FosUserBundle将数据发送到javascript,如

php_sapi_name()

然后在javascript中你可以使用JSON.parse使它成为一个javascript对象

json_encode

答案 1 :(得分:0)

使用json_encode

echo json_encode($markersData);

在JS中解析它:

res = JSON.parse(markersData, function(a,b){ return b;});
   alert(res);