Условный пропуск строки при отображении таблицы - PullRequest
0 голосов
/ 27 октября 2018

У меня есть папки с каждым файлом index.html, который просто содержит заголовок.

Сейчас я пытаюсь убедиться, что если папка пуста, мы не показываем ее на доске, ноЯ не знаю, как это сделать ...

Я также отправляю вам часть кода, чтобы вы лучше поняли мой запрос:

$title     = array();
$link_html = array();

// Find title and file inside the folder
$fileList = glob('tpe**/index.html');
foreach($fileList as $file_Path) {
    $html = file_get_contents($file_Path);
    preg_match("/<title>([^<]*)<\/title>/im", $html, $matches);
    array_push($title, $matches[1]);
    array_push($link_html, $file_Path);  
} 

$file_empty = glob('tpe**');
foreach($file_empty as $filePath) {
    if (count(glob($filePath . '/*')) == 0 ) {
        /* Gérer condition dossier vide */
    }
}

// Loops through the array of files
for($index=0; $index < $indexCount; $index++) {
    // Allows ./?hidden to show hidden files
    if ($_SERVER['QUERY_STRING']=="hidden") {
        $hide  = "";
        $ahref = "./";
        $atext = "Hide";
    } else {
        $hide=".";
        $ahref="./?hidden"; 
        $atext="Show";
    }
    if (substr("$dirArray[$index]", 0, 1) !== $hide) {
        // Gets File Names
        $name=$dirArray[$index];

        // Gets Date Modified Data
        $modtime=date("Y-m-d H:i", filemtime($dirArray[$index]));

        // Display all information
        $dirs1    = array_filter(glob('*'),'is_file');
        $compteur = count($dirs1)+2;

        if ($index>=$compteur) {
            $ind = $index - $compteur;
            $path = $link_html[$ind];
            print("
                <tr>
                <td><a href='./$path'>$name</a></td>
                <td><a href='./$path'>$modtime</a></td>
                <td><a href='./$path'>$title[$ind]</a></td>
                </tr>" 
            );
        }
    }
}       

На этом изображении папка tpe07пуст, поэтому цель состоит в том, чтобы не отображать пустые папки:

enter image description here

1 Ответ

0 голосов
/ 28 октября 2018

Я сделал тест с этим деревом ниже.Здесь .tpe05 является скрытым каталогом, а tpe07 пустым.

.
├── index.php
├── tpe00
│   └── index.html
├── tpe01
│   └── index.html
├── tpe02
│   └── index.html
├── tpe03
│   └── index.html
├── tpe04
│   └── index.html
├── .tpe05
│   └── index.html
├── tpe06
│   └── index.html
├── tpe07
├── tpe08
│   └── index.html
└── tpe09
    └── index.html

Давайте рассмотрим скрипт:

<?php

$title     = array();
$link_html = array();

// Code added to make this test page working
// You can remove it since dirArray and indexCount
// seem to be already set in your code.
date_default_timezone_set('Europe/Paris');
$dirArray = array();
for ($i=0; $i <= 9 ; $i++)
    array_push($dirArray,($i==5?".":null)."tpe0" . $i);
$indexCount = sizeof($dirArray);
// End of added code

// Getting *all* the files including the hidden ones.
// Getting also the hidden files.
// Filling title and link_html arrays for each file
// With <key,value> pairs.
// Examples:
// $title["tpe01"] = "Je suis index 01"
// $link_html["tpe01"] = "tpe01/index.html"

$fileList = glob('{,.}tpe*/index.html', GLOB_BRACE);
foreach($fileList as $file_Path) {
    $html = file_get_contents($file_Path);
    preg_match("/<title>([^<]*)<\/title>/im", $html, $matches);
    $dirname = basename(dirname($file_Path));
    $title[$dirname] = $matches[1];
    $link_html[$dirname] = $file_Path;
} 

// Code added to make this test page working (HTML table beginning)
// You can remove it since it seems you already begun the table.
echo "<table>";
// End of added code

// Loops through the array of files
for($index=0; $index < $indexCount; $index++) {
    // Allows ./?hidden to show hidden files

    $name=$dirArray[$index];
    $hasDirPrefix = (substr($name, 0, 1) == ".");

    if ($hasDirPrefix && !$showHiddenFile) continue;
    if (!isset($title[$name])) continue;

    // Gets File Names


    // Gets Date Modified Data
    $modtime=date("Y-m-d H:i", filemtime($dirArray[$index]));


    $path = $link_html[$name]; // . ($showHiddenFile?"?hidden":null);
    print("
                <tr>
                <td><a href='./$path'>$name</a></td>
                <td><a href='./$path'>$modtime</a></td>
                <td><a href='./$path'>$title[$name]</a></td>
                </tr>" 
    );


}
// Code added to make this test page working (HTML table end)
// You can remove it since it seems you may have end the table
// further.
echo "</table>";
// End of added code
?>

Здесь я использовал continue.Согласно документации PHP :

continue используется в структурах цикла для пропуска остальной части итерации текущего цикла и продолжениявыполнение при оценке состояния и затем начало следующей итерации .

Я также использовал ассоциативные массивы для заголовков и ссылок,Это стало намного легче получить их после.Посмотрите содержимое массива заголовков:

Array
(
    [tpe00] => Je suis index 0
    [tpe01] => Je suis index 1
    [tpe02] => Je suis index 2
    [tpe03] => Je suis index 3
    [tpe04] => Je suis index 4
    [tpe06] => Je suis index 6
    [tpe08] => Je suis index 8
    [tpe09] => Je suis index 9
    [.tpe05] => Je suis index 5
)

Чтобы получить заголовок каталога tpe04, просто напишите title["tpe04"].Вам не нужно обращать внимание на элементы заказа, что хорошо для нас: в $fileList, ".tpe05" - последний элемент, сделайте print_r($fileList);, чтобы увидеть его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...