Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Alison Mercer
Alison Mercer
46 Points

SOLVED: Trying to set a multidimensional array within foreach in PHP and then send to Javascript, not working?

SOLVED if you get the below from a PHP array in Javascript, you need to set an id outside of a PHP loop ($id = 1) then increment it in the array as the first associative item, id -> $id++ then use that id to call each item iterating through the list in javascript.

To pass it to javascript, first use JSON encode in PHP, $json_array=json_encode($phparray); .Then simply echo the array in a PHP block, which is inside a javascript block like so <script>var array = <?php echo $phparray ?>;</script> and finally do this in JS after you have the array variable set from PHP, array = JSON.parse(array);.

  1. [object Object]
  2. [object Object]
  3. [object Object]
  4. [object Object]
  5. [object Object]
  6. [object Object]
  7. [object Object]

3 Answers

Pieter Bracke
Pieter Bracke
4,078 Points

As above you need to parse JSON otherwise it does not understand the data inside of the the array Also you are looping through the array why are you not using i++ in your for loop? what are you obtaining by stating i+= 1 ?

Zachary Billingsley
Zachary Billingsley
6,187 Points

Hello!

Try using 'films = JSON.parse(films);' after you get the json_encode string from PHP. I believe javascript needs that to be able to understand it as an object.

Hope that helps!