PHP数组问题
这更多的是一个关于 PHP 和数组的内置功能的概念问题。我想知道是否有任何方法可以执行以下操作:
您有一个数组 $a
,并且出于本示例的目的,该数组包含 5 个元素 (0-4)。
有没有办法制作一个新数组,其中包含以下内容:
$b[0] = $a[0];
$b[1] = $a[0] + $a[1];
$b[2] = $a[0] + $a[1] + $a[2];
$b[3] = $a[0] + $a[1] + $a[2] + $a[3];
$b[4] = $a[0] + $a[1] + $a[2] + $a[3] + $a[4];
etc..
我想它的使用示例是网站上的面包屑,您可以在其中单击给定链接的任何目录,例如 /dir1/dir2 /dir3/dir4
PHP 中是否有内置的东西可以处理以这种方式构建数组?或者处理这个问题的函数的例子?或者甚至是更好的方法来解决这个问题。
谢谢!
编辑:这是在你们的帮助下的最终解决方案!这将构建链接,并为每个目录/元素创建正确的链接。
//$a is our array
$max = count($a);
foreach (range(1,$max) as $count) {
$b[] = implode("/", array_slice($a, 0, $count));
}
foreach($b as $c) {
$x = explode('/' , $c);
$y = array_pop($x);
echo "<a href='$c'>".$y."</a>"."/";
}
This is more of a conceptual question concerning the built in functionality of PHP and arrays. I was wondering if there is any way to do the following:
You have an array $a
and this array contains 5 elements (0-4) for the purpose of this example.
Is there any way to make a new array, which would contain the following:
$b[0] = $a[0];
$b[1] = $a[0] + $a[1];
$b[2] = $a[0] + $a[1] + $a[2];
$b[3] = $a[0] + $a[1] + $a[2] + $a[3];
$b[4] = $a[0] + $a[1] + $a[2] + $a[3] + $a[4];
etc..
I imagine an example of it's use would be bread crumbs on a website, where you could click on any directory of a given link like /dir1/dir2/dir3/dir4
Is there anything built into PHP that can handle building up an array in this fashion? Or examples of a function which handles this? Or even a better way to go about this.
Thanks!
EDIT: Here is the final solution via the help of you guys! This will build the link, and create the proper link for each directory/element.
//$a is our array
$max = count($a);
foreach (range(1,$max) as $count) {
$b[] = implode("/", array_slice($a, 0, $count));
}
foreach($b as $c) {
$x = explode('/' , $c);
$y = array_pop($x);
echo "<a href='$c'>".$y."</a>"."/";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您只想要示例中的五种组合,那么:
If you just want the five combinations as in your example then:
在这种情况下,最好使用递归函数。
未经测试,但应该可以。它将使每个顺序值包含数组中位于其之前的值。
You'd be best with a recursive function in that case.
Untested, but should work. It will make each sequential value contain the values before it in the array.
我想,你想要这样的东西:
I think, you want something like this: