I'm trying to take an array of array in PHP, and convert it to a javascript array with new text formatting in JSON Format. What is the best practice for making formatting changes while converting array to JSON?
I have tried using json_encode when I brought array to Javascript... but that seems to be creating a JS array that is a string thereby making .map return an error. I can get the .map function to work on a single variable containing a hard code of my array. I can't get .map to make the format changes when i just convert my php array to a json array. I have also tried doing the format change one result at a time as it comes out in the MySQL query, and nothing I try is working. I'm very new to JS so struggling with the details of array conversion and json reformatting combined.
var myFences = [];
var jfences = <?php echo json_encode($fences)?>;// puts php array into json formatting into js.
var myFences = Array.from(jfences);
myFences = myFences.map ( e => ({lat: e[0], lng: e[1]}) ) ;
console.log(myFences);
var myFences = [$jfences[1]];
let path = jfence;
path = path.map ( e => ({lat: e[0], lng: e[1]}) ) ;
The output of the php array looks like this:
Array
(
[0] => [[56.51845972498524, -6.182719791640125],
[56.52412387806186, -6.18409308265575],
[56.523103365873006, -6.1784282572162965]]
[1] => [[58.472119674062085, -8.168053780198875],
[58.47303462652167, -8.161809597612205],
[58.46960999252895, -8.160264645219627]]
)
But I need it to be a JS array in json format with text changes like this:
var geofence = [
{lat: 56.51845972498524, lng: -6.182719791640125},
{lat: 56.52412387806186, lng: -6.175282560388155},
{lat:56.523103365873006,lng: -6.147215925256319}
];
here is the code used to generate the php array:
$sql = "SELECT `poly_data` FROM `landowner_polygon` WHERE `landowner_location_id`=".$llocID;
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>poly_data</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['poly_data'] . "</td>";
$llocFence = $row['poly_data'];
$allFences = $allFences.$llocFence;
$fences[] = $llocFence;
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
}