I'm pulling the url parameter and I'm trying to create a breadcrumb out of it. So, if I pull:
$url = 'contact/jane/now';
and I do:
$path = explode("/",$url);
How can I put it in a loop so that it breaks each part into a path like this:
<a href="/contact">contact&l开发者_如何学运维t;/a>
<a href="/contact/jane">jane</a>
<a href="/contact/jane/now">now</a>
$answer = '';
foreach ($path as $path_part){
$answer .= '/'.$path_part;
print('<a href="'.$answer.'">'.$path_part.'</a>');
}
Pre PHP 5.3:
array_reduce($path, create_function('$a, $b', '
echo "<a href=\"$a/$b\">$b</a>\n";
return "$a/$b";
'));
In PHP 5.3:
array_reduce($path, function($a, $b) {
echo "<a href=\"$a/$b\">$b</a>\n";
return "$a/$b";
});
You can use a For, For Each, Do, Do While, While. Really whatever you want. http://php.net/manual/en/control-structures.for.php When your explode it turns it into an array of strings http://us.php.net/manual/en/function.explode.php
So, just use the count() method and determine how many elements are in the array http://us.php.net/manual/en/function.count.php
And then go ahead and loop through and read one at a time. If you want to start at the last and then go backwards you simply change your loop to go initialize at the count of the array then subtract one each time from your counter. Otherwise, just do it as normal.
Yay for looking on the PHP doc!
You could use array_slice for that the code is not really tested but I hope you get the idea
...
$url = explode('/', $url);
$links = array();
for ($i = 0; $i < count($url); $i++) {
$crumb = ($i > 0) ? implode('/', array_slice($url, 0, $i)) .'/' : $url[$i] .'/';
$links[] = sprintf('<a href="%s">%s</a>', $crumb . $url[$i], $url[$i]);
}
精彩评论