开发者

Rearrange php array to javascript array problem

开发者 https://www.devze.com 2023-03-12 03:32 出处:网络
I have a group of PHP array data like this: $xx_add = array( array(\'id\'=>1, \'name\'=>\"jiahui shop\", \'description\' => \"Jl. Sukarjo Wiryopranoto No. 69 A, Pasar Baru\", \'lat\'=>-6.

I have a group of PHP array data like this:

$xx_add = array(
    array('id'=>1, 'name'=>"jiahui shop", 'description' => "Jl. Sukarjo Wiryopranoto No. 69 A, Pasar Baru", 'lat'=>-6.249650, 'lng'=>106.850288),
    array('id'=>2, 'name'=>"Success United Pte Ltd", 'description' =>"Atrium Plaza Blok E Unit 122 5 Jl. Senen Raya No. 135 Senen, Jakarta Pusat", 'lat'=>-6.167170, 'lng'=>106.873894),
    array('id'=>3, 'name'=>"Chilis Restaurant, Lt. 2, Jl. MH. Thamrin No. 11, Sarinah", 'description' =>"Sarinah Building, Lt. 2, Jl. MH. Thamrin No. 11, Sarinah", 'lat'=>-6.197090, 'lng'=>106.738213)
); 

How can I do, so that I can get a bundle of javascript array as like shown below?

var $xx_add = [
    {'id': 1, 'name': 'jiahui shop', 'description': 'Jl. Sukarjo Wiryopranoto No. 69 A, Pasar Baru', 'lat': -6.249650, 'lng': 106.850288 }, 
    {'id': 2, 'name': 'Success United Pte Ltd', 'description': 'Atrium Plaza Blok E Unit 122 5 Jl. Senen Raya No. 135 Senen, Jakarta Pusat'开发者_C百科, 'lat': -6.167170, 'lng': 106.873894 }, 
    {'id': 3, 'name': 'Chilis Restaurant', 'description': 'Sarinah Building, Lt. 2, Jl. MH. Thamrin No. 11, Sarinah', 'lat': -6.197090, 'lng': 106.738213 }
];

Thank you


Are you trying to get JSON code from PHP? Use json_encode() function:

http://php.net/manual/en/function.json-encode.php

Then you'll need to add the variable declaration. :)


Convert to JSON:

json_encode($xx_add);

See http://php.net/manual/en/function.json-encode.php


I use json_encode.


You can also embed PHP in your JavaScript block (which is the most ugly solution I can think of):

<?php
    $xx_add = array(...);
?>

<script>
    var xx_add = <?php json_encode($xx_add); ?>
</script>


JSON encode it

echo "var xx_add = jQuery.jsonParse('".json_encode($xx_add).'");";
0

精彩评论

暂无评论...
验证码 换一张
取 消