同时在php中使用2 foreach循环从目录中检索文件名

时间:2019-05-16 18:36:58

标签: php html foreach

我正在处理如下所示的php代码,其中我试图检索 mp4和xml文件的名称

$src_dir    = 'incoming_folder';  /* Place where mp4 file is present */
$mp4_files = preg_grep('~\.(mp4)$~', scandir($src_dir)); /* Line #Y */
print_r($mp4_files);     /* Line #A */ 
$xml_files = preg_grep('~\.(xml)$~', scandir($src_dir)); /* Line #Z */
print_r($xml_files); /* Line #B */   

Line#A打印以下内容:

Array ( [2] => 45017P.mp4 [3] => 45031P.mp4 [5] => hello.mp4 

行#B打印以下内容:

Array ( [2] => 45017.xml [5] => 45031P.xml [7] => hello.xml )

我在下面的html中集成了 Line#Y Line#Z 代码,以便从目录中检索文件名。

<table width="100%">
   <tr>
      <!-- This inline css will go inside addiional css -->
   </tr>
   <th style="width:8%;">House#</th>
   <th style="width:8%;">Date</th>
   <th style="width:8%;" >Time</th>
   <th style="width:8%;">MP4</th>
   <th style="width:8%;" >XML</th>
   <?php    foreach ($mp4_files as $file ) {
      foreach ($xml_files as $file2 ) {     
      ?>
   <tr>
      <td style="width:8%; text-align:center;"> <?php echo basename($file, ".mp4"); ?></td>
      <td style="width:8%; text-align:center;"><?php echo date("F d Y",filemtime("incoming_folder/$file")); ?></td>
      <td style="width:8%; text-align:center;"><?php echo date("H:i:s",filemtime("incoming_folder/$file")); ?></td>
      <td style="width:8%; text-align:center;"> <?php echo basename($file); ?></td>
      <td style="width:8%; text-align:center;"> <?php echo basename($file2); ?></td>
   </tr>
   <?php
      }
      }
      ?>
</table>

上面的 html / php 代码显示以下内容:

House#      Date          Time         MP4         XML
45017P  April 30 2019   10:21:12    45017P.mp4  45017P.xml
45017P  April 30 2019   10:21:12    45017P.mp4  45031P.xml
45017P  April 30 2019   10:21:12    45017P.mp4  hello.xml
45031P  May 01 2019     14:56:56    45031P.mp4  45017P.xml
45031P  May 01 2019     14:56:56    45031P.mp4  45031P.xml
45031P  May 01 2019     14:56:56    45031P.mp4  hello.xml
hello   April 30 2019   10:21:12    hello.mp4   45017P.xml
hello   April 30 2019   10:21:12    hello.mp4   45031P.xml
hello   April 30 2019   10:21:12    hello.mp4   hello.xml

问题陈述:

在上面的House#列的o / p中,我可以看到两个45017P,两个45031P和两个hello。我想知道如何避免冗余,以便显示如下内容:

House#    Date           Time           MP4       XML
45017P  April 30 2019   10:21:12    45017P.mp4  45017P.xml 
45031P  May 01 2019     14:56:56    45031P.mp4  45031P.xml
hello   April 30 2019   10:21:12    hello.mp4   hello.xml

0 个答案:

没有答案