nkk
nkk

Reputation: 43

How to convert php array to js array?

I have a php array which i need to convert and assign that to var locationsArray

required format:

var locationsArray = [
    ['Google Official','1600 Amphitheatre Parkway, Mountain View, USA'],
    ['Google 1','112 S. Main St., Ann Arbor, USA'], 
    ['Google 2','10 10th Street NE, Suite 600 USA']
];

Upvotes: 0

Views: 4378

Answers (4)

nkk
nkk

Reputation: 43

    foreach ($address as $key => $val){
                                    $val = strip_tags($val);
                                    $points[] = array($val, $val);
                                }
                                $json = json_encode($points);
                                $json = str_replace('\n',' ',$json);
                                $json = str_replace('\r',' ',$json);

var locations = '<?php echo $json;?>';
var locations_array = JSON.parse(locations);

var locationsArray = locations_array;

Upvotes: 2

GautamD31
GautamD31

Reputation: 28763

Try like

$NewJsonData = json_encode(locationsArray);
echo $NewJsonData;  //Alert it in javascript   

Try this LINK

You can assign the variable $NewJsonData to your js variable

Upvotes: 0

Jayram
Jayram

Reputation: 19578

This will help you.

<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>

Upvotes: 0

karaxuna
karaxuna

Reputation: 26930

This will be something like:

<script type="text/javascript">
    var locationsArray = <?php echo json_encode(array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5)); ?>
</script>

Don't know php syntax, sorry :) ref

Upvotes: 0

Related Questions