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));

TA貢獻1811條經驗 獲得超6個贊
從Get specific element from each sub array 中獲取,您需要使用 array_column 來獲取特定的子數組值。
$coords = array_column($coordinates, 'coordinates'); $sites = array_column($coordinates, 'sites');
我無法在我身邊測試它,因為我不在 PC 上。請讓我知道這是否有效。
- 2 回答
- 0 關注
- 173 瀏覽
添加回答
舉報