PHP array into Javascript Array

前端 未结 4 574
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 23:32

Afternoon all. The code below works perfectly, however, I need to pull each row of the php sql array out and into the script var. Any ideas on how to write a while loop that cou

相关标签:
4条回答
  • 2021-01-24 00:09

    Hope this would help

      <?php 
        $res = mysql_fetch_assoc($result)
        foreach($res as $key => $val){ ?>
                enableDays.push('<?php echo $val; ?>');
        <?php } 
      ?>
    
    0 讨论(0)
  • 2021-01-24 00:14

    Pull your data out into a PHP array, then transfer that to JavaScript with

    var enableDays = <?php echo json_encode($enableDays); ?>;
    

    As an aside, the obligatory recommendation that you should stop using the PHP mysql extension immediately because it is not very safe and has been deprecated; switch to something better (mysqli and PDO are both good choices).

    0 讨论(0)
  • 2021-01-24 00:17

    This can't work. Once the page is loaded, all the PHP has run already. But if you're really just adding the next mysql_result for each push, you could have PHP create the entire enableDays array for you:

    <?php
      echo 'var enableDays = ["' . mysql_result(...) . '", "' . mysql_result(...) . '"];'
    ?>
    
    0 讨论(0)
  • 2021-01-24 00:18

    You can get the rows using mysqli_fetch_assoc and then encode it to JSON:

    <?php
    $rows = array();
    
    while ($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
    }
    ?>
    
    
    var enableDays = <?php echo json_encode($rows); ?>;
    
    0 讨论(0)
提交回复
热议问题