我需要一些幫助。
我在 php 中有這個陣列:
Array (
[0] => Array (
[name] => Ville1
[description] => adresse1
[lng] => -10.35
[lat] => 29.1833
)
[1] => Array (
[name] => Ville2
[description] => description2
[lng] => 12.61667
[lat] => 38.3833
)
)
如何將其轉換為這種格式并在 javascript 中添加物件?
locations: {
"0": {
lat: "48.3833",
lng: "12.61667",
name: "Ville1",
description: "adresse1"
},
"1": {
lat: "29.1833",
lng: "-10.35",
name: "Ville2",
description: "adresse2"
}
},
謝謝和對不起英語..
uj5u.com熱心網友回復:
解決方法很簡單。您唯一需要做的就是將陣列傳遞給 php 函式json_encode。
這將自動將您的陣列轉換為 JSON。
同樣,您也可以將 PHP 物件轉換為 JSON。
最后,還有另一個 PHP 函式,其名稱json_decode正好相反。如果您有 JSON 字串,則可以將其轉換為 PHP 陣列或物件。
唯一的區別是,當您轉換 JSON 物件時,在 PHP 中您會獲得stdClass實體。
<?php
$array = [
[
"name" => "Ville1",
"description" => "adresse1",
"lng" => -10.35,
"lat" => 29.1833
],
[
"name" => "Ville2",
"description" => "description2",
"lng" => 12.61667,
"lat" => 38.3833
]
];
$jsonStructure = json_encode($array);
?>
<script>
var locations = <?php echo $jsonStructure; ?>;
// The following line should print in your browser console
// the word: Ville1
console.log(locations[0].name);
</script>
uj5u.com熱心網友回復:
做完之后 => $jsonStructure = json_encode($array); 我在 php 中的陣列是:
[{"name":"Ville1","description":"adresse1","lng":-10.35,"lat":29.1833},{"name":"Ville2","description":"description2","lng":12.61667,"lat":38.3833}]
我愿意:
<script>
var locations = <?php echo $jsonStructure; ?>;
// The following line should print in your browser console
// the word: Ville1 => YES IT'S TRUE BUG NOT WHAT I WANT :)
console.log(locations);
myObjet.location = locations;
</script>
查看螢屏: 在此處輸入影像描述
但這不是好的格式,它必須是這樣的:
locations: {
"0": {
lat: "48.3833",
lng: "12.61667",
name: "Ville1",
description: "adresse1"
},
"1": {
lat: "29.1833",
lng: "-10.35",
name: "Ville2",
description: "adresse2"
}
},
uj5u.com熱心網友回復:
請相應地更新您的 PHP 代碼。它應該對你有用。
$array = [
[
"name" => "Ville1",
"description" => "adresse1",
"lng" => -10.35,
"lat" => 29.1833
],
[
"name" => "Ville2",
"description" => "description2",
"lng" => 12.61667,
"lat" => 38.3833
]
];
foreach ($array as $keys => $value ) {
$object->{$keys} = $value;
}
$jsonStructure = json_encode($object);
echo $jsonStructure;
輸出應該是這樣的:
{
"0": {
"name": "Ville1",
"description": "adresse1",
"lng": -10.35,
"lat": 29.1833
},
"1": {
"name": "Ville2",
"description": "description2",
"lng": 12.61667,
"lat": 38.3833
}
}
現在您可以將其$jsonStructure用于您的 javascript。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/351785.html
標籤:javascript php
