【问题标题】:how to push arrays in array and NOT concatenate?如何在数组中推送数组而不是连接?
【发布时间】:2015-06-15 06:16:01
【问题描述】:

我有以下 php 代码,它给出了一个名为“markers”的数组变量。

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: 如果有人觉得有必要对我的问题投反对票,请告诉我原因,以便我可以学到一些东西。

【问题讨论】:

  • 发布您的预期输出并输入
  • 您会看到连接的数组,因为您正在警告数组,完成后调用加入数组的 toString() 函数。尝试使用console.log(window.markers) 并在控制台中查看您应该看到数组结构。
  • 你不需要双括号。单括号是正确使用:window.markers.push(['arrayItem1', 'arrayItem2']);。使用 console.log(window.markers) 检查您的输出。
  • 或者,如果您仍然喜欢使用警报,请执行 alert(JSON.stringify(window.markers)); 以查看数组结构。
  • 你们都非常正确!哇,今天学到东西了。事实上,我的代码一直都在工作,只是因为“错误”的警告消息而停止完成它!谢谢!!

标签: javascript php arrays


【解决方案1】:

由于 cmets:
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],
[... ,... , ... ,...],
];

【讨论】:

  • 您可以插入更多括号,以分隔数据集;直接在while (...) 之后和endwhile 之前。最后一个逗号无关紧要。
  • 这个答案中最初发布的代码的结果不是我想要的。我需要括号中的数组作为数据集。 @Nina:猜猜这就是我需要的,但恐怕不明白括号的确切位置。顺便问一句:为什么push方法不好?因为它给了我想要的输出。
  • @Garavani datasets 意思是你想要 {'center_name': 'First center', 'center_address': 'First Address', ..}? Push 不好,因为它需要被执行。如果您可以创建纯脚本来节省一些客户端 CPU 活动,为什么还需要这个?显示准确您需要的内容。
  • @Garavani:这里是... &lt;?php while( have_rows('actin_center') ): the_row(); ?&gt;["&lt;?php the_sub_field('center_name'&lt;?php the_sub_field('longitude'); ?&gt;],&lt;?php endwhile ...
  • 谢谢大家。我会坚持推送解决方案(是 ACF 插件的人给我解决这个问题的解决方案。它工作正常。用 befzzs 代码尝试了一些东西但没有用。要准确显示我需要的内容,请参阅原始帖子。数组“标记”是期望的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 2016-03-25
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
相关资源
最近更新 更多