我正在 loop
中的 php
中创建关联数组,如下所示:
$coordinates[] = array("coordinates"=>[$lat, $lng], "site"=>"ext");
$coordinates[] = array("coordinates"=>[$lat, $lng], "site"=>"curr");
这给出:
[0]=>
array(2) {
["coordinates"]=>
array(2) {
[0]=>
string(18) "40.836132854296686"
[1]=>
string(17) "8.404270310882566"
}
["site"]=>
string(4) "curr"
}
[1]=>
array(2) {
["coordinates"]=>
array(2) {
[0]=>
string(10) "40.8998985"
[1]=>
string(9) "9.5177142"
}
["site"]=>
string(4) "curr"
}
[2]=>
array(2) {
["coordinates"]=>
array(2) {
[0]=>
string(17) "40.71976910000001"
[1]=>
string(17) "8.563560499999994"
}
["site"]=>
string(3) "ext"
}
}
现在我需要推送每个对坐标,例如:
["coordinates"]=>
array(2) {
[0]=>
string(10) "40.8998985"
[1]=>
string(9) "9.5177142"
}
进入 JS
数组,并对另一个具有 [site]
值的数组执行相同的操作,例如:
["site"]=>
string(3) "ext"
在 JS
中我这样做:
var coordsJson = '<?php echo json_encode($coordinates); ?>';
var coords = JSON.parse(coordsJson);
console.log(coordsJson);
这给了我:
[{"coordinates":["40.836132854296686","8.404270310882566"],"site":"curr"},{"coordinates":["40.8998985","9.5177142"],"site":"curr"},{"coordinates":["40.71976910000001","8.563560499999994"],"site":"ext"}]
我需要coords
是一个有效的数组,并将一对坐标作为对象,并将[site]
推送到像site = []这样的数组
但我不确定如何从关联数组中获取值。
我试图插入
myCoords.push(coords['coordinates']);
但这是错误的。我相信我应该循环 json
响应,但是如何 push
到 JS
呢?
更新
我基本上需要这样结构的js数组:
0: (2) ["40.836132854296686", "8.404270310882566"]
1: (2) ["40.8998985", "9.5177142"]
2: (2) ["40.71976910000001", "8.563560499999994"]
并且具有相同的但对于数组site[]
,字面上寻找2个数组coords[]
和site[ ]
最佳答案
与原生 PHP 相比,在 JavaScript 中使用数组是一种乐趣。您始终可以使用循环,但我倾向于采用函数方法。
首先,让我们简化将数据从 PHP 转移到 JS 的过程:
var coordsJson = '<?php echo json_encode($coordinates); ?>';
var coords = JSON.parse(coordsJson);
您不需要将其包装在字符串中然后解析。
const coordinates = <?php echo json_encode($coordinates); ?>;
我应该注意,我的示例将用 ES6 编写。
接下来我们可以使用map来构建包含我们需要的数据的新数组。
// this could be a one liner but expanding for explanatory purposes.
const coordinatePairs = coordinates.map((coordinate) => {
// here we're using the spread operator to expand our object.
// it's a simple way to convert an object into an array.
return [...coordinate.coordinates];
});
现在让我们遵循一个类似但更简单的网站流程。
const sites = coordinates.map((coordinate) => (coordinate.site));
关于javascript - 如何将 php 关联数组中的值推送到 jquery 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57301443/