1

I have an array $lines in php. Currently I want to assign the $lines value to a javascript variable(i.e. chartLines).

The way I assigned the php array to javascript is not correct.

Can anyone help me? Thanks in advance!

<?php
    $line1 = array(array("08:00","20"),array("08:00","16"),array("08:00","19"),array("08:00","17"));

    $line2 = array(array("08:00","45"),array("08:00","47"),array("08:00","49"),array("08:00","47"));

    $lines= array($line1,$line2);  
?>


 <script type="text/javascript">
    $(function () {

        var chartLines = <?php echo $lines; ?>  

                });
2
  • Use var chartLines = <?php json_encode($lines); ?>; Commented Nov 1, 2011 at 16:42
  • why don't you output your array data into the javascript itself? meaning <? $a=''; $a.='<script> function(){ var q=".$myArray.";'; ?> etc Commented Nov 1, 2011 at 16:44

4 Answers 4

1

Try this way:

<?php
    $line1 = array(array("08:00","20"),array("08:00","16"),array("08:00","19"),array("08:00","17"));

    $line2 = array(array("08:00","45"),array("08:00","47"),array("08:00","49"),array("08:00","47"));

    $lines= array($line1,$line2);  
    $json = json_encode($lines);
?>

 <script type="text/javascript">
    $(function () {

        var chartLines = jQuery.parseJSON('<?php echo $json; ?>  ');

                });
1
  • i think converting array to JSON then to JS array and including Jquery is a little hard and no need for it , echo the JS array is the simplest thing Commented Nov 1, 2011 at 16:46
0

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

0

you can try this :

<?php
# create PHP array:
$php_array = array("one", "two", "three");

echo "<script language='JavaScript'>\n";

echo "var js_array = new Array();\n";

$ix = 0;

foreach($php_array as $key => $value)
{
echo "js_array[$key] = $value;\n";
}

echo "</script>\n";
0

Your best bet is to use the json_encode PHP function suggested by others here, like this:

<?php
  $chartLines = array("item1" => "val1", "item2" => "val2", "item3" => "val3");
  $chartJSON = json_encode($chartLines);
?>

<script type="text/javascript">
  var chartLines = jQuery.parseJSON('<?php echo $chartJSON; ?>');
</script>

If you need an array on the JS side too (not an object which is what parseJSON will return), you can use jQuery to do that too:

var chartArr = jQuery.makeArray(chartLines);

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.