6

Is these a way i can loop through a PHP array and have the data outputted into a JavaScript array?

For example, the JS script below will not work

var mon_Loop = <?php echo $rowCount_Mon ?>;
var mon_Events = new Array();
for(i = 0; i < mon_Loop; i++)
{ 
   mon_Events[i] = <?php $divMon[i] ?>
}

I Know its because the "i" is not a php variable so therefore invalid inside the php section, but its just an way to show what i would like to achieve. The $rowCount variable count the number of rows and is then used to for the loop. Lets say, for example that I want to place the contents of the PHP array "$divMon[0]" into the javascript array mon_Events[0].

I know that i can do it manually, like below

mon_Events[0] = <?php echo $divMon[0] ?>

But i have lots of these and therefore need the loop, Is there some JS or PHP that could do this?

Cheers.

1 Answer 1

11

Since it seems that your array $divMon contains numeric indexes, you can simply serialize it using json_encode:

var array = <?php echo json_encode($divMon) ?>;
//...
2
  • Thank you so much, this has helped to no end. Much Appreciated! Commented May 17, 2010 at 1:10
  • 1
    Plus use the JSON_HEX_TAG argument if you are inside a <script> block, to prevent any </script> sequences from prematurely ending the script. Commented May 17, 2010 at 1:34

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.