0

I am new to JavaScript arrays and finding it difficult to manipulate them with php arrays. I have an array in php which has some values

PHP Array

Array
(
    [0] => Array
        (
            [0] => 7
            [id] => 7
            [1] => state1
            [state_name] => state1
            [2] => 26.200604
            [latitude] => 26.200604
            [3] => 92.937574
            [longitude] => 92.937574
        )
    [1] => Array
        (
            [0] => 3
            [id] => 3
            [1] => state1
            [state_name] => state2
            [2] => 25.198009
            [latitude] => 25.198009
            [3] => 85.521896
            [longitude] => 85.521896
        )
)

How can I assign values in a JavaScript array like

var reach = [
                {
                    latitude:'22.996155', 
                    longitude:'72.306519',
                    location:'state1'
                },
                                {
                    latitude:'22.996155', 
                    longitude:'72.306519',
                    location:'state2'
                }
]
Haseeb
  • 2,214
  • 1
  • 22
  • 43
Nitish Hardeniya
  • 181
  • 2
  • 15

3 Answers3

0

You need to first traverse the array to remove unwanted keys (like numeric keys + id). Then you can use json_encode method:

<?php

foreach ($array as $values) {
  unset($values[0]);
  unset($values['id']);
  .. other unsets..
}

?>
<script type="text/javascript">
var reach = <?=json_encode($array)?>
</script>
mesutozer
  • 2,839
  • 1
  • 12
  • 13
0
use json_encode($array); for encoding array in json format 
use json_decode($array,TRUE); for converting json string to array
PravinS
  • 2,640
  • 3
  • 21
  • 25
0

It looks like your array is indexed by both column name and 0-indexed column number, if you don't want the numeric index, then change your fetch type from FETCH_BOTH to FETCH_ASSOC(just for example).

Then you could just encode the array by json_encode() function.

<script type="text/javascript">
var reach = <?= json_encode($array) ?>;
</script>
xdazz
  • 158,678
  • 38
  • 247
  • 274