I have a string like this : Indoformosa/Folder1/SubFolder1
, and with those string will be generate an array for a breadcrumbs URL. The app needs an array format lke this:
[
0 => [
'label' => 'Indoformosa'
'url' => 'Indoformosa'
]
1 => [
'label' => 'Folder1'
'url' => 'Indoformosa/Folder1'
]
2 => [
'label' => 'SubFolder1'
'url' => 'Indoformosa/Folder1/SubFolder1'
]
]
So far, my PHP code looked like this:
$queryParamsPath = 'Indoformosa/Folder1/SubFolder1'
$links = explode('/', $queryParamsPath);
$links = array_map(function ($el) {
return [
'label' => $el,
'url' => Url::to($el)
];
}, $links);
The output looked like this:
[
0 => [
'label' => 'Indoformosa'
'url' => 'Indoformosa'
]
1 => [
'label' => 'Folder1'
'url' => 'Folder1'
]
2 => [
'label' => 'SubFolder1'
'url' => 'SubFolder1'
]
]
2
Answers
An easy fix would introducing an extra array in which you wil ‘hold’ to url, and append the next part on each iteration:
Try it online!
A more dynamic fix would using
array_reduce()
, where you can use thecarry
to get the ‘last’url
, and append the currenturl
to it, with a/
between if it’s not the first one:Try it online!
Both provide the following output:
You were actually pretty close. I slightly change your code to use more standard language elements:
You might want to put this inside a function to isolate the variables from the global scope.
You can see the working code here: https://3v4l.org/Y6dSc