【问题标题】:How to create links in Dropdown List using PHP variables?如何使用 PHP 变量在下拉列表中创建链接?
【发布时间】:2020-08-13 17:58:04
【问题描述】:

我想显示目录的内容并将它们的超链接插入到下拉列表中。 这是我的代码。

<select>
    <?php
$dir = "/";

// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
        $target = dirname($_SERVER['PHP_SELF']);
            $target=$target.$file;
            ?>
            <option value="<?php $target ?>"><?php $file ?></option>   
          <?php
         }    
    closedir($dh);
  }
}
?>
</select> 

我得到的只是一个空白列表。

【问题讨论】:

  • 我建议不要将逻辑与渲染混合。

标签: php list hyperlink dropdown


【解决方案1】:

我建议你使用类来包装你的逻辑。 :-)

<?php declare(strict_types=1);
final class Finder
{
    /** @var string */
    private $path;
    public function __construct(string $path)
    {
        $this->path = $path;
    }
    public function folderNames(): array
    {
        if (!is_dir($this->path)) {
            throw new \Exception('Path is not a directory');
        }
        if (!$directory = opendir($this->path)) {
            throw new \Exception('The directory can not be open');
        }
        $directories = [];
        while (($file = readdir($directory))) {
            if (is_dir($file)) {
                $directories[] = $file;
            }
        }
        return $directories;
    }
}
// Usage example:
$dropdown = new Finder($_SERVER['PHP_SELF']);
$directories = $dropdown->folderNames();
echo '<select>';
foreach ($directories as $directory):
    echo "<option value=\"{$directory}\">{$directory}</option>";
endforeach;
echo '</select>';

理想情况下,您应该在另一个文件中包含“用法示例”部分。该文件代表一个模板,它接收$directories 列表,模板只需要呈现它。

【讨论】:

    【解决方案2】:

    这不会输出值:

    <?php $target ?>
    

    您需要echo 或使用= 速记。例如:

    <option value="<?php echo $target; ?>"><?php echo $file; ?></option>
    

    或:

    <option value="<?= $target ?>"><?= $file ?></option> 
    

    【讨论】:

    • 它成功了,现在我可以看到一个正确的列表,但是当我点击它们时仍然看不到指向 $target 的元素。
    • @KunalAren:“看不到指向 $target 的元素” - 你能详细说明你的意思吗?
    • 我希望每个元素($file)都应该链接到下拉列表中的地址($target)。现在所有元素都在列表中可见,但它们没有链接到 ($target)。
    • @KunalAren:在这种情况下,您所说的“链接到”是什么意思?显示的代码仅呈现带有&lt;option&gt;s 的&lt;select&gt; 元素,没有显示任何形式或任何逻辑的代码。如果您有一些其他代码无法以其他方式运行,这听起来像是另一个 Stack Overflow 问题的基础。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多