简体   繁体   中英

How do I convert php array of array into js array with using .map to reformat

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


}

Use .map to map over the array, and use .flat() function to flatten the array.

const geoFence = jfences.map((item) => {
  return item.map(geo => {
    return {
      lat: geo[0],
      log: geo[1]
    }
  })
}).flat()

 const jfences = [[[56.51845972498524,-6.182719791640125],[56.52412387806186,-6.18409308265575],[56.523103365873006,-6.1784282572162965]],[[58.472119674062085,-8.168053780198875],[58.47303462652167,-8.161809597612205],[58.46960999252895,-8.160264645219627]]] const geoFence = jfences.map((item) => { return item.map(geo => { return { lat: geo[0], log: geo[1] } }) }).flat(); console.log(geoFence) 

Without .flat()

 const jfences = [[[56.51845972498524,-6.182719791640125],[56.52412387806186,-6.18409308265575],[56.523103365873006,-6.1784282572162965]],[[58.472119674062085,-8.168053780198875],[58.47303462652167,-8.161809597612205],[58.46960999252895,-8.160264645219627]]] const fencesArrObj = jfences.map((item) => { return item.map(geo => { return { lat: geo[0], log: geo[1] } }) }) const geoFence = [].concat.apply([], fencesArrObj); console.log(geoFence) 

That is what I am using:

function jsonObjToArray(jsonObj) {
  var result = [];

    var keys = Object.keys(jsonObj);

    keys.forEach(function (key) {
        result.push(jsonObj[key]);
    });

    return result;
}

I think that is fast way to achieve what you need.

Try the following snippet

 var a = [ [ [56.51845972498524, -6.182719791640125], [56.52412387806186, -6.18409308265575], [56.523103365873006, -6.1784282572162965] ], [ [58.472119674062085, -8.168053780198875], [58.47303462652167, -8.161809597612205], [58.46960999252895, -8.160264645219627] ] ] a = a.map(b => { return b.map((c, i) => { return { lat: c[0], lng: c[1] } }) }) console.log(a) 

Here is the modified code it will return the output as per your requirement.

var myFences = [];
var jfences = <?php echo json_encode($fences)?>;// puts php array into json formatting into js.
jfences.forEach(array => {
    array.map(e => {
        myFences.splice(myFences.length, 0, ({lat: e[0], lng: e[1]}));
    });
}); 
console.log(myFences);


// Output of myFences var
   [
      {"lat": 56.51845972498524,"lng": -6.182719791640125},
      {"lat": 56.52412387806186,"lng": -6.18409308265575},
      {"lat": 56.523103365873006,"lng": -6.1784282572162965},
      {"lat": 58.472119674062085,"lng": -8.168053780198875},
      {"lat": 58.47303462652167,"lng": -8.161809597612205},
      {"lat": 58.46960999252895,"lng": -8.160264645219627}
    ]

or let me know if you want something else...

Thank you everyone for your input... It turns out my array coming out of PHP was not an array, but a string that looked like an array... I would like to take credit for this solution, but I was schooled by an awesome architect I know, and he gave me a single line to solve this. All the code you guys provided worked, except my original array was broken so it wasn't a complete fix. Here is the answer.

var myFences = Array.from(<?php echo json_encode($fences)?>).map(e => eval(e).map(p => ({lat:p[0],lng:p[1]})));

console.log(myFences)

This returns a properly formatted array that I can use to create the right output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM