PHP array into Javascript Array

守給你的承諾、 提交于 2019-12-31 04:06:26

问题


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 could do this? Thanks for any help

 var enableDays = ["<?php echo mysql_result($result, 0, 'date'); ?>"];

 enableDays.push("<?php echo mysql_result($result, 1, 'date'); ?>");

Additional Code::

$rows = array();

while ($row = mysql_fetch_assoc($result))
{
    $rows[] = $row;
}



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

    console.log(enableDays[1]);

回答1:


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); ?>;



回答2:


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).




回答3:


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(...) . '"];'
?>



回答4:


Hope this would help

  <?php 
    $res = mysql_fetch_assoc($result)
    foreach($res as $key => $val){ ?>
            enableDays.push('<?php echo $val; ?>');
    <?php } 
  ?>


来源:https://stackoverflow.com/questions/18059638/php-array-into-javascript-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!