PHP array issue

This is more of a conceptual question about the built-in functionality of PHP and arrays. I was wondering if there is a way to do the following:

You have an array of $a , and this array contains 5 elements (0-4) for this example.

Is there a way to create a new array that will 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 assume that breadcrumbs on a website where you can click on any directory of this link, for example /dir1/dir2/dir3/dir4 , will be an example of its use /dir1/dir2/dir3/dir4

Is there anything built into PHP that can handle an array this way? Or examples of a function that handles this? Or even the best way to do it.

Thanks!

EDIT: Here is the final solution with the help of you guys! This will create a link and create the correct link for each directory / item.

 //$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>"."/"; } 
+6
source share
4 answers

If you just need five combinations, as in your example, follow these steps:

 foreach (range(1,5) as $count) { $b[] = implode("/", array_slice($a, 0, $count)); } 
+4
source

In this case, you will be better off with a recursive function.

 $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); } 

Unconfirmed, but should work. This will make each consecutive value containing the values ​​before it in the array.

+1
source
 $b = array(); for($i=0;$i<count($a);$i++) { $b[] = array_sum(array_splice($a,0,$i)); } 
+1
source

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]; 
0
source

Source: https://habr.com/ru/post/889838/


All Articles