簡體   English   中英

如何在數組中推送數組而不是連接?

[英]how to push arrays in array and NOT concatenate?

我有以下 php 代碼,它提供了一個名為“標記”的數組變量。

window.markers = [];

<?php if( have_rows('actin_center') ): ?>
<?php while( have_rows('actin_center') ): the_row(); ?>

window.markers.push( [ ['<?php the_sub_field('center_name'); ?>', '<?php the_sub_field('center_address'); ?>', <?php the_sub_field('latitude'); ?>, <?php the_sub_field('longitude'); ?>] ] );

<?php endwhile; ?>
<?php endif; ?>

到目前為止,這工作正常,但返回數組(處於警報狀態)為:

Cool center 1,Rewitz Gofella, 1234 Lorem,50,50,Cool center 2,Lorem Ipsum, 1234 Quosque,60,60,Cool center 3,Veniat elaborat, 1234 Ipsum,70,70

然而,我需要的是以下形式,保留數組(子字段),因為它們最初位於數組內,而不是連接它們。 作為:

var markers = [
    ['First Center','First Address',50,50],
    ['Second Center','Second Address', -25.363882,131.044922],
    ['Third Center','Third Address', 10.363882,95],
    ['Fourth Center','Fourth Address', -50,-90],
    ['Fifth Center','Fifth Address', 30,5],
];

正如您在上面的代碼中看到的那樣,我嘗試使用簡單的雙括號 [[]] 但這不起作用。 如何正確地做到這一點? 非常感謝您的幫助。

PS:如果有人覺得有必要對我的問題投反對票,請告訴我為什么這樣我可以學到一些東西。

由於評論:
alert( [[1,2][3,4]] )會彈出錯誤的1,2,3,4
alert( JSON.stringify([[1,2][3,4]])會彈出[[1,2],[3,4]]

.push([1,2])將添加一個數組markers : [[1,2],[3,4],[5,6]]
.push(1,2)元素添加到markers : [1,2,3,4,5,6]

但更好的方法是不要執行 javascript .push (節省客戶端 CPU 時間)
以這種方式在javascript中定義數組:

window.markers = [
<?php while( have_rows('actin_center') ): the_row(); ?>
  ["<?php the_sub_field('center_name');?>","<?php the_sub_field('center_address'); ?>",<?php the_sub_field('latitude');?>, <?php the_sub_field('longitude');?>],
<?php endwhile; ?>
];

結果應該是這樣的

window.markers = [
['First Center', 'First Address', 50, 50],
['Second Center','Second Address',-25.363882, 131.044922],
[... ,... , ... ,...],
];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM