【问题标题】:PHP add array value after echoedPHP 在回显后添加数组值
【发布时间】:2022-11-14 23:07:48
【问题描述】:

我正在创建一个 Web 应用程序,我想在其中包含 JavaScript 文件以及数组中的所有文件源,但我不能这样做,请帮助

我的代码

头文件.php

<head>
<?php
  $import_scripts = array(
    'file01.js',
    'file02.js'
  );

  foreach ($import_scripts as $script) {
    echo '<script src="' . $script . '"></script>';
  }
?>
</head>
<body>

索引.php

<?php
  include('header.php');
  array_push($import_scripts,'file03.js')
?>

但这仅包括 file01.js 和 file02.js,JavaScript 文件。

抱歉,如果您无法理解这一点

【问题讨论】:

    标签: php arrays foreach array-push


    【解决方案1】:

    您的问题是,当您将新值推送到 index.php 中的数组时,您已经在 headers.php 中回显了脚本。所以你需要添加额外的脚本你包括headers.php。这是一种方法(在未设置 $extra_scripts 时使用空合并运算符来防止错误):

    头文件.php

    <?php
      $import_scripts = array_merge(array(
        'file01.js',
        'file02.js'
      ), $extra_scripts ?? []);
    
    ?>
    <!DOCTYPE html>
      <html>
        <head>
          <!-- Scripts Section -->
    <?php
      foreach ($import_scripts as $script) {
        echo '<script src="' . $script . '"></script>' . PHP_EOL;
      }
    ?><title>Demo</title>
        </head>
        <body>
          <p>Blog</p>
    

    索引.php

    <?php
      $extra_scripts = ['file03.js'];
      include('header.php');
    ?>
    

    输出 (demo on 3v4l.org)

    <!DOCTYPE html>
      <html>
        <head>
          <!-- Scripts Section -->
    <script src="file01.js"></script>
    <script src="file02.js"></script>
    <script src="file03.js"></script>
    <title>Demo</title>
        </head>
        <body>
          <p>Blog</p>
    

    【讨论】:

    • 如果我使用它,我的脚本将在正文而不是头部导入。你可以通过任何功能来做,我不是告诉你只用array_push()来做。但我想把剧本放在头脑而不是身体
    • @CodemasterUnited 问题,问题中并不清楚。请看我的编辑。
    • 我需要先包含标题,然后导入脚本
    • @CodemasterUnited 此代码将包含 index.php 中的脚本header.php 中的脚本。这不是你想要的吗?
    猜你喜欢
    • 2012-02-25
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多