将PHP数组转换为JavaScript对象

Converting PHP array to JavaScript Object

本文关键字:JavaScript 对象 转换 PHP 数组      更新时间:2023-09-26

我遇到麻烦了!由于我对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

您应该使用json_encode将数据发送到类似的javascript

echo json_encode($markersData);

然后在javascript中,您可以使用JSON.parse使其成为javascript对象

response = JSON.parse(markersData, function(k,v){
                    return v;
                });
    console.log(response);

使用json_encode:

echo json_encode($markersData);

在JS中解析它:

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