How to insert a PHP array into a javaScript array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Claus Mygind
    Contributor
    • Mar 2008
    • 571

    How to insert a PHP array into a javaScript array

    I was looking for a simple way to create a javaScript array when streaming out my php code.

    my php sql query generates a quick rowset result in an associative array like this.
    Code:
    if ( $result = $db->query($sql) )
    {
      if ($result->num_rows > 0)
      {
        $f = mysqli_fetch_all( $result, $resulttype = MYSQLI_ASSOC );
      }
    }
    Then when streaming out the page, inserting the following in the page header
    Code:
    <script type="text/javascript">
      var exportArray = <?php echo $f;?>;
    </script>
    But of course this simple example simply generates a javaScript array with no content.

    Is it only possible to copy this data using two loops. Where in outer loop you cycle through the php array. And in the inner loop you cycle through each column of that specific row?

    What I was looking for was a better way.

    When streaming out my page to the client computer, I was looking for a quick way to insert this data into a javaScript array on the resulting page web page. I was hoping not to have to loop through the php array and extract each column in each row.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    I was looking for a simple way to create a javaScript array when streaming out my php code.
    json_encode() ?

    Comment

    Working...