为了账号安全,请及时绑定邮箱和手机立即绑定

如何将值从 php 关联数组推送到 jquery 数组?

如何将值从 php 关联数组推送到 jquery 数组?

PHP
陪伴而非守候 2021-11-05 18:39:36
我创建的关联数组php中的一个loop是这样的:$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[]
查看完整描述

2 回答

?
墨色风雨

TA贡献1853条经验 获得超6个赞

与原生 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));


查看完整回答
反对 回复 2021-11-05
?
杨魅力

TA贡献1811条经验 获得超6个赞

Get specific element from each sub array 中获取,您需要使用 array_column 来获取特定的子数组值。

$coords = array_column($coordinates, 'coordinates');
$sites = array_column($coordinates, 'sites');

我无法在我身边测试它,因为我不在 PC 上。请让我知道这是否有效。


查看完整回答
反对 回复 2021-11-05
  • 2 回答
  • 0 关注
  • 148 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信