Javascript和PHP为每个循环输出一个数组


Javascript and PHP for each loop to output an array

我正试图使用从php数据库中提取的内容创建一个javascript数组。

<?php
//This creates an array from the database and allows us to use it later in the jquery
//CREATE SQL STATEMENT
$sql_locations = "SELECT * FROM tbllocations";
//CONNECT TO MYSQL SERVER
require('test-connection.php');
//EXECUTE SQL STATEMENT
$rs_locations = mysqli_query($vconnection, $sql_locations);
$rs_locations_rows = mysqli_fetch_assoc($rs_locations);
foreach( $rs_locations as $rs_location ) {
  $markers[] = array(
      "{$rs_location['place']}, {$rs_location['city']}",
     $rs_location['long'],
      $rs_location['lat']
  );
}
?>
<div id="map_wrapper">
    <div id="map_canvas" class="mapping"></div>
</div>

<style>
    #map_wrapper {
        height: 400px;
    }
    #map_canvas {
        width: 100%;
        height: 100vh;
    }

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
    function initialize() {
        var map;
        var bounds = new google.maps.LatLngBounds();
        var mapOptions = {
            mapTypeId: "roadmap",
            center: new google.maps.LatLng(47.608941, -122.340145), // somewhere in the uk BEWARE center is required
            zoom: 3,
        };
        // Display a map on the page
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        map.setTilt(45);
        // Multiple Markers
        var markers = <?php echo json_encode( $markers ); ?>;
        // Info Window Content
        var infoWindowContent = [
            <?php while($rs_location_rows = mysqli_fetch_assoc($rs_location)) { ?>
            ['<div class="info_content">' +
            '<h3><?php echo $rs_locations_rows['branch']; ?></h3>' +
            '<p><?php echo $rs_locations_rows['content']; ?></p>' + 
            '<p><?php echo $rs_locations_rows['phone']; ?></p>' + 
            '</div>']
            <?php } ?>

        ];
        // Display multiple markers on a map
        var infoWindow = new google.maps.InfoWindow();
        var marker, i;
        // Loop through our array of markers & place each one on the map
        for (i = 0; i < markers.length; i++) {
            var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
            bounds.extend(position);
            marker = new google.maps.Marker({
                position: position,
                map: map,
                title: markers[i][0]
            });
            // Allow each marker to have an info window
            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infoWindow.setContent(infoWindowContent[i][0]);
                    infoWindow.open(map, marker);
                }
            })(marker, i));
            // Automatically center the map fitting all markers on the screen
            map.fitBounds(bounds);
        }
        //Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {
            this.setZoom(10);
            google.maps.event.removeListener(boundsListener);
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);

</script>

我已经更新了代码以显示我的整个页面。在此期间,我尝试了这个while循环,并在中添加它可以阻止我的页面生成和输出我的地图,所以我的页面将挂起。

我想用与标记相同的方式为每个循环做一个,但到目前为止我还没有成功

因为你基本上是在尝试构建一个包含一些js代码的字符串,然后将其直接传递给浏览器,所以我会用PHP构建一个字符串,然后一次性回显。更容易看到你在做什么。

<?php
$js = '<script type="text/javascript">';
$js .= 'var infoWindowContent = [';
while( $row = mysqli_fetch_assoc($rs_location)) { 
    $js .= "['" . '<div class="info_content">';
    $js .= "<h3>{$row['branch']}</h3>";
    $js .= "<p>{$row['content']}</p>";
    $js .= "<p>{$row['phone']}</p>";    
    $js .= "</div>'],";    
}
// trim off the js interpreter breaking trailing comma
$js = rtrim( $js, ',' );
// close the outer array
$js .= '];';
$js .= '</script>';
echo $js;
?>

您只需要将do while结构更改为while:正如@RiggsFilly所提到的。(对不起,我现在明白了)

var infoWindowContent = [
    <?php while($rs_location_rows = mysqli_fetch_assoc($rs_location)) { ?>
    ['<div class="info_content">' +
    '<h3><?php echo $rs_locations_rows['branch']; ?></h3>' +
    '<p><?php echo $rs_locations_rows['content']; ?></p>' + 
    '<p><?php echo $rs_locations_rows['phone']; ?></p>' + 
    '</div>'],
    <?php } ?>
];

这是我要使用的方法:

var myArray = [
    <?php while ($rs_location_rows = mysqli_fetch_assoc($rs_location)) : ?>
    {
        'branch' : '<?= $rs_locations_rows["branch"] ?>',
        'content' : '<?= $rs_locations_rows["content"] ?>',
        'phone' : '<?= $rs_locations_rows["phone"] ?>'
    },
    <?php endwhile; ?>
];
console.log(myArray);

现在您的js中有了数组。