PHP中面包屑的数组结构

时间:2014-02-19 19:46:03

标签: php arrays

我想在我的页面上显示面包屑。我的网址与domain.com/customer-management/list类似。我使用$_SERVER["REQUEST_URI"]来获取这些内容,然后通过/对它们进行爆炸以获取数组。

目前,我有以下数组

$paths = array(
    "index.php" => "Home",
    "index.php/customer-management" => "Customer management",
    "index.php/customer-management/list" => "Customer list",
    "index.php/customer-management/new" => "New customer",
    "index.php/account" => "Me",
    "index.php/account/change-password" => "Change password"
);

在我的代码中,我循环遍历所有分解的值,并从数组中获取相应的文本表示。

for($i = 0; $i < sizeof($crumbs); $i++) {
    $parts = array();
    for($a = 0; $a <= $i; $a++) {
        $parts[] = $crumbs[$a];
    }

    $path = join("/", $parts);

    echo "<li>" . $paths[$path] . "</li>";
}

这很有效,但是当我有很多子页面用于客户管理时,我必须重复customer-management/部分。我怎么能把它变成一个多维数组?

我认为这种阵列更容易维护。

$paths = array(
    "customer-management" => array(
        "" => "Customer management",
        "list" => "Customer list",
        "new" => "New customer"
    ),
    "account" => array(
        "" => "Me",
        "change-password" => "Change password"
    )
);

但是,如何访问这些密钥?我如何递归循环呢?

2 个答案:

答案 0 :(得分:0)

这对于不存在的路径没有错误检查,但应该让您走上正确的轨道:

$pathAr = array(
    "customer-management" => array(
        "" => "Customer management",
        "list" => "Customer list",
        "new" => "New customer"
    ),
    "account" => array(
        "" => "Me",
        "change-password" => "Change password"
    )
);

function findTitle($crumbs, $pathAr){

  if(!is_array($crumbs)) $crumbs = explode("/", $crumbs);
  $crumb = array_shift($crumbs);

  if(is_array($pathAr[$crumb])){
    return findTitle($crumbs, $pathAr[$crumb]);
  }else{
    return $pathAr[$crumb];
  }

}

$title = findTitle("customer-management/list", $pathAr);

echo $title;

答案 1 :(得分:0)

如果您使用建议的数组,则可以将其重组为新数组,如下所示:

foreach ($paths AS $path_section => $path_location_array) {

    foreach ($path_location_array AS $path_location_url => $path_location_title) {

        $path_location_key = preg_replace('~//~', '/', 'index.php/'.$path_section.'/'.$path_location_url);

        $new_array[$path_location_key] = $path_location_title;

    }

}