【问题标题】:PHP, Create dynamic list from files in a directoryPHP,从目录中的文件创建动态列表
【发布时间】:2015-06-15 15:46:13
【问题描述】:

我有一个文件目录,其主要目的是存储 php 变量以包含在站点中的其他文件中。每个文件都包含相同的变量集,但具有不同的值。

例如:

event1.php

<?php
  $eventActive = 'true';
  $eventName = My First Event;
  $eventDate = 01/15;
?>

event2.php

<?php
  $eventActive = 'true';
  $eventName = My Second Event;
  $eventDate = 02/15;
?>

除了在其他页面中调用这些变量之外,我还想根据目录内每个文件中存储的变量创建一个包含动态列表的页面。

类似(基本概念):

for each file in directory ('/events') {
  if $eventActive = 'true'{ 
    <p><? echo $eventName ?></p>
  }
}

最好的方法是什么?

【问题讨论】:

    标签: php list variables foreach directory


    【解决方案1】:

    好的,所以我花了一些时间来解决这个问题,但使用了一个更简洁的解决方案,但使用了一个外部 json 文件来存储值

    <?php
    
        $json = file_get_contents('events.json');
    
        $jsonArray = json_decode($json, true); // decode the JSON into an associative array
    
        foreach ($jsonArray as $value) {
    
            if (($value['active'] === 't') && ($value['fromDate'] >= $currentDate)) {
    
                echo '<p>'.$value['title'].' '.$value['fromDate'].' - '.$value['toDate'].'</p>';
            }
        }
    
        echo $currentDate;  
    ?>
    

    【讨论】:

      【解决方案2】:

      为每个事件创建一个Event 类或array。然后从目录中填充它。

      $index = 0;
      foreach (array_filter(glob($dir.'/*'), 'is_file') as $file) {
        @include $file; // Parses the file, so the variables within are set.
        $events[$index]['active'] = $eventActive;
        $events[$index]['name'] = $eventName;
        $events[$index]['date'] = $evetnDate;
        $index++;
        // OR
        // $events[] = new Event($eventName, $eventDate, $eventActive);
      }
      // Now the $events array contains all your events.
      // List out the active ones
      foreach ($events as $event) {
        echo ($event['active'] === 'true') ? $event['name'] : '';
        // OR
        // echo $event->isActive() ? $event->getName() : '';
      }
      

      【讨论】:

      • 感谢您的反馈。如何按名称或类型排除特定文件?
      • 按名称,您可以创建一个排除名称的数组,例如$exclude = ['file1.php', 'file2.php', ...];,并添加一个if (in_array($file, $exclude) { // Skip it }。至于 type 我必须查找如何在 PHP 中确定文件的类型。如果您可以使用文件扩展名,则知道$file 很可能是file_name.ext,因此您可以使用其中一个字符串操作函数来确定扩展名并采取行动。
      猜你喜欢
      • 2018-01-16
      • 2015-08-17
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      相关资源
      最近更新 更多