繁体   English   中英

如何将 PHP 变量的 while 循环作为 JSON 组件传递到 JS 脚本中?

[英]How do you pass a while loop of PHP variables into a JS script as JSON components?

我正在尝试用事件填充 JS 日历(fullCalendar 插件)。 我有适当的 PHP 代码使用 SQL 从我的数据库中提取信息:

$item_results = $mysqli->query($sql_items);
$item_row = $item_results->fetch_assoc();

我已将此 output 放入 while 循环中,以便将所有单个结果重写为 JSON 格式:

$events = '';

while ( $item_row = $item_results->fetch_assoc() ) {
    $events .= '{title: \''. $item_row['item'] . '\', start: \'' . $item_row['expiration_date'];
    $events .= '\', color: \'' . $color . '\'' . '}, ';
  }

但是,当我插入'<?php echo $events; ?>' '<?php echo $events; ?>'在我的 PHP 代码下方的 JS 脚本标记中,它对日历没有任何 output 任何内容。

var Calendar = new FullCalendar.Calendar(CalendarEl, {
  events: [
   // {
   //   title: 'conference',
   //   start: '2020-02-11'
   // }
   '<?php echo $events; ?>';
 ]});

重新开始并将 PHP 变量拆分为 arrays 这样我可以使用json_encode()会更好吗? 在这种情况下,我将如何处理事件的 rest?

为什么不先用数组再用json_encode

$events = [];

while ( $item_row = $item_results->fetch_assoc() ) {
    $events[] = ["title" => $item_row['item'], "start" => $item_row['expiration_date'], "color" => $color];
  }

$events = json_encode($events,JSON_PRETTY_PRINT);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM