使用for循环创建子目录

时间:2018-12-13 10:23:45

标签: php loops for-loop directory

 $product_Category = ' Electronics| Computers & Accessories| Monitors ';   

<!-- a simple div with some links --> 
    <div class="breadcrumb-killer flat">
        <a href="index.php" class="active">Home</a>
        <?php 
        $cats = explode("|",  $product_Category);
        for($k = 0; $k < count($cats); $k++) {
            for ($l=0; $l <= $k; $l++) { 
                $folder = permalink($cats[$l])."/" ;
                echo $folder;
            }

            echo '<a href="'.$folder.'">'.$cats[$k].'</a>';
        } 
        ?>
    </div>

我将类别分隔为-电子产品|电脑及配件|显示器

使用此功能创建干净的url

function permalink($var)
{
    $var = preg_replace('#([\W_]+)#', ' ', $var);
    $var = str_replace(' ', '-', $var);
    $var = strtolower($var);
    $var = rtrim($var, '-');
    $var = ltrim($var, '-'); 
    $var = trim($var);
    return $var;
}

当我的输出文件夹收到此消息时:

electronics/  electronics/computers-accessories/ electronics/computers-accessories/monitors/

尽管urs并非按照我想要的方式构建。 我希望网址像:

<a href="electronics/">Electronics</a>
<a href="electronics/computers-accessories/">Computers & Accessories</a>
<a href="electronics/computers-accessories/monitors/">Monitors</a>

这就是我得到的:

    <a href="electronics/">Electronics</a>
    <a href="computers-accessories/"> Computers &amp; Accessories</a>
    <a href="monitors/"> Monitors</a>

1 个答案:

答案 0 :(得分:0)

刚刚意识到我的错误-内部的for循环是将各个部分加在一起,但并不是添加它们而只是替换它们,您需要使用.=对其进行重置并添加每个段……

    $folder = "";
    for ($l=0; $l <= $k; $l++) { 
        $folder .= permalink($cats[$l])."/" ;
        // echo $folder;
    }