Reputation: 67
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>"."/";
}
Upvotes: 6
Views: 128
Reputation: 57287
$b = array();
for($i=0;$i<count($a);$i++) {
$b[] = array_sum(array_splice($a,0,$i));
}
Upvotes: 1
Reputation: 1496
I think, you want something like this:
for($i = 0; $i < count($a); $i++)
for($j = 0; $j < i + 1; $j++)
$b[i] += $a[j];
Upvotes: 0
Reputation: 145492
If you just want the five combinations as in your example then:
foreach (range(1,5) as $count) {
$b[] = implode("/", array_slice($a, 0, $count));
}
Upvotes: 4
Reputation: 2116
You'd be best with a recursive function in that case.
$arr = array('dir1', 'dir2', 'dir3', 'dir4', 'dir5');
function breadcrumbs($a)
{
// Remove first value
$first = array_shift($a);
// Loop through other values
foreach ($a as $key => $value)
{
// Add first to remaining values
$a[$key] = $first . '/' . $value;
}
// Return array
return array($first) + breadcrumbs($a);
}
Untested, but should work. It will make each sequential value contain the values before it in the array.
Upvotes: 1