The problem with your approach:
"The code I'm using is on an separate js file that is called into my php page with <script></script>
is that the script is being processed on the client without ever being seen by PHP, so it cannot process the contents of the <?php ... ?>
block. Hence your output of <?php echo $package[2]['pages'] ?>
. To make this work you need to output the data into an array/object in the .php file (the json_encode
approach suggested by @user1491032 and @coletrain is a good one) and then access that array in your script file i.e.
PHP file:
echo "<script>var package = JSON.parse('" . json_encode($package) . "');</script>";
JS file:
info = package[packID]['pages'];
Update
As was pointed out by @DavidBélanger, you don't need to use JSON.parse
if the object is well built, you can just assign the variable directly i.e. in the PHP file:
echo "<script>var package = " . json_encode($package) . ";</script>";
and in the JS
info = package[packID].pages;