在 <Div> if() echo 语句中排列标签



我试图打印出php目录中的文件,并在一个列表中排列文本文件,在另一个列表中排列jpg文件(在相同的水平高度,并排)

<!DOCTYPE html>
<html>
<body>
<?php
    $files = scandir('uploads');
    foreach($files as $file){
        $extension = pathinfo($file,PATHINFO_EXTENSION);
        if($extension == 'txt') {
            echo'<div style="text-align:center; margin-left:-120px;"> <br><a href="uploads/'.$file.'">'.$file.'</a></div>';
        }
        if($extension == 'jpg') {
            echo'<div style="text-align:center; margin-right:-120px;"> <br><a href="uploads/'.$file.'">'.$file.'</a></div>';
        }
    }
?>
</body>
</html>

目录中有以下文件:

test.txt hello.txt test.jpg hello.jpg

它给我的输出是:(在屏幕中间

          test.jpg
          hello.jpg
test.txt
hello.txt

但是我想要这样的东西(在页面中间),其中。txt文件首先出现。

          test.txt   test.jpg
          hello.txt  hello.jpg

我试过添加一个css元素' float:left;',然后将该类添加到div',但这并不能解决问题。

我也试过使用:display: inline-block;无效

给你

div {
  text-align: center;
box-sizing: border-box;
  border: 1px solid black;
  width: 50%;
  float:left;
}
<div>
  <ul>
  <li><a href="files/hello.txt">Hello.txt</a></li>
  <li><a href="files/test.txt">Test.txt</a></li>
  </ul>
</div>
<div>
  <ul>
  <li><a href="files/hello.txt">Hello.jpg</a></li>
  <li><a href="files/test.txt">Test.jpg</a></li>
  </ul>
</div>

这是您的php代码的修订版,请将其与示例中提供的CSS一起尝试。

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
        div {
  text-align: center;
box-sizing: border-box;
  border: 1px solid black;
  width: 50%;
  float:left;
}
</style>
</head>
<body>
<?php
    $filetypes = ['txt','jpg']; //with the following code you'll be able to add other fileextensions as you need them
    foreach ($filetypes as $ext) {
     $files = glob('uploads/*.'.$ext.'');
     echo '<div><ul>';
       foreach($files as $file){
            echo'<li><a href="'.$file.'">'.(explode('/',$file)[1]).'</a></li>';
       }
     echo '</ul></div>';
     }
?>
</body>
</html>

如果要输出某种格式,请先对数据进行排序。例如,让你的数据是一个数组[test.txt, test.jpg, hello.txt, hello.jpg],然后像这样循环:

foreach($data as $key=>$val){
    echo $val;
    if($key%2==0) echo '    ';//here is xx.txt, so you can write your css to make it in the beginning of line
    else echo "n";// here is xx.jpg, make it clear right or append it a <br>
}

最新更新