0

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']
];
1
  • Can you show your php array please
    – Dale
    Commented Jun 11, 2013 at 7:03

4 Answers 4

2
    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;
0

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

2
  • Array ( [0] => 30 South Wacker Drive Floor 22 Chicago IL 60606 [1] => 288 Bishopsgate London, EC2M 4QP United Kingdom [2] => 260 Madison Avenue 8th Floor New York NY 10016 [3] => 315 Montgomery Street 8th Floor San Francisco CA 94104
    – nkk
    Commented Jun 11, 2013 at 7:37
  • need to make like "locationsArray" and assign equal to js var in given format.
    – nkk
    Commented Jun 11, 2013 at 7:38
0

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>
1
  • it is assigning the value to javascript_array, but not in the format I required(format shown in the question)
    – nkk
    Commented Jun 11, 2013 at 7:41
0

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

8
  • [stackoverflow.com/questions/17036886/…
    – nkk
    Commented Jun 11, 2013 at 6:20
  • what is the link...??you got the ans there or what
    – GautamD31
    Commented Jun 11, 2013 at 6:21
  • this js variable is fixed....need to assign php array equal to this variable in same format like it is.
    – nkk
    Commented Jun 11, 2013 at 6:21
  • link is for more description, havn't got the answer yet
    – nkk
    Commented Jun 11, 2013 at 6:22
  • yes the result value $NewJsonData ,you can assign it to js variable
    – GautamD31
    Commented Jun 11, 2013 at 6:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.