0

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


}
  • 1
    why not create a PHP endpoint who returns the array in json and request it with AJAX ? – Constantin Guidon May 08 '19 at 09:29
  • What's the `myFences` array look like after you've modified it with `map`? Looks like the code would be fine. – Jack Bashford May 08 '19 at 09:30
  • Show us how you make `$fences` Thats where you need to make changes. Fix the problem, dont fudge it – RiggsFolly May 08 '19 at 09:37
  • I don't know Ajax, but will do some research on how i might do that. myFences won't modify with .map as an array because I think it's a string... I think that is my issues as the php array is coming over as a string (i could be wrong there). Here is the MySQL loop that builds the myFences array. – Steve Flynn May 08 '19 at 09:53
  • I'm wondering if it's how I'm creating myFences in php that is causing my issue... i added code above. – Steve Flynn May 08 '19 at 09:56
  • I'm getting suggestions below which are awesome and they are all close.. but I think I'm creating the original php array incorrectly in the MySQL section, because when I take your solutions which output the reformatted json, and I replace it with my array... i get an error in the console: 'TypeError: item.map is not a function'. Ive looked around and can't see an obvious explanation for what is causing this. thank you all for you input so far. – Steve Flynn May 08 '19 at 17:48

5 Answers5

1

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)
Junius L
  • 15,881
  • 6
  • 52
  • 96
0

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.

0

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)
Shridhar Sharma
  • 2,337
  • 1
  • 9
  • 13
  • thnk you for doing this... it seems to be returning a single array with six objects rather than an array with two. I think I need an array with keys? rather than one array with 6 objects holding lat longs from two sets. (make sense?) here is what the output looks like: (6) […] ​ 0: Object { lat: 56.51845972498524, lng: -6.182719791640125 } ​ 1: Object { lat: 56.52412387806186, lng: -6.18409308265575 } ​ 2: Object { lat: 56.523103365873006, lng: -6.1784282572162965 } ​ 3: Object { lat: 58.472119674062085, lng: -8.168053780198875 } ​ 4: Object .... etc ​ length: 6 – Steve Flynn May 08 '19 at 17:42
  • That is getting closer... can i ask, how do i get from an array with objects in it, to something like this: 0: (3) […] ​ 0: Object { lat: 56.51845972498524, lng: -6.182719791640125 } 1: Object { lat: 56.52412387806186, lng: -6.18409308265575 } var geofence = [ {lat: 53.523341487842316, lng: -6.193736158410616}, {lat: 53.535126839526605, lng: -6.175282560388155}, etc... ] Would that be a for loop to remove the Object? Or is there a command that converts the objects within the area? This is as close as I've gotten. – Steve Flynn May 09 '19 at 09:47
  • can you please post what are you getting and what exactly you want? – Shridhar Sharma May 09 '19 at 09:50
  • Shridhar, how do I do that? I'm new here and don't want to get the protocol wrong. Do I post that in the section above? Or here? It's an awesome group and just want to learn the right way to interact. – Steve Flynn May 09 '19 at 10:21
0

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... i'll give this a try. – Steve Flynn May 08 '19 at 11:44
  • this gets close, but i get a console error 'TypeError: array.map is not a function'. If i output jfence directly to the console before the foreach loop... it looks correct. like this: 0: "[[53.51845972498524, -6.182719791640125],[53.52412387806186, -6.18409308265575]]" 1: "[[52.472119674062085, -8.168053780198875]]. this error is what i keep hitting, and it's like the array is not working. Someone suggested it might be a string... – Steve Flynn May 08 '19 at 17:35
  • If the `var jfences = ` return a valid JSON array then the above code works fine, I created this code for a valid PHP array which is mentioned by you in your question, you just need to replace this javascript code it works fine. or send me the screenshot of the javascript code after page load. – Narayan Sikarwar May 09 '19 at 05:50
  • Thank you... yes the problem for me is my json_encode step is not returning a valid json array... When I do a print_r on the php array just before the conversion, it looks like this: (Seems ok ... but I know there is something wrong). Array ( [0] => [[53.51845972498524, -6.182719791640125],[53.52412387806186, -6.18409308265575]] [1] => [[52.472119674062085, -8.168053780198875],[52.47303462652167, -8.161809597612205] ) – Steve Flynn May 09 '19 at 09:55
0

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.