php - parse - ¿Cómo combinar múltiples url/path en una matriz multidimensional?
php string tokenizer (2)
Todo lo que necesita es la función explode () y los bucles foreach.
Tengo una matriz como esta:
$path = array (
[0] => site/projects/terrace_and_balcony/mexico.jpg
[1] => site/projects/terrace_and_balcony/new_york.jpg
[2] => site/projects/terrace_and_balcony/berlin.jpg
[3] => site/projects/terrace_and_balcony/Kentucky.jpg
[4] => site/projects/terrace_and_balcony/Utah.jpg
[5] => site/projects/terrace_and_balcony/Hawaii.jpg
[6] => site/projects/private_gardens/mexico.jpg
[7] => site/projects/private_gardens/new_york.jpg
[8] => site/projects/private_gardens/berlin.jpg
[9] => site/projects/private_gardens/Kentucky.jpg
[10] => site/projects/private_gardens/Utah.jpg
[11] => site/projects/private_gardens/Hawaii.jpg
)
Cómo convertirlo a eso:
$path11 = array
(
"site"=>array
(
"projects"=>array
(
"terrace_and_balcony"=>array
(
"mexico.jpg",
"new_york.jpg",
"berlin.jpg",
"Kentucky.jpg",
"Utah.jpg",
"Hawaii.jpg"
),
"private_gardens"=>array
(
"mexico.jpg",
"new_york.jpg",
"berlin.jpg",
"Kentucky.jpg",
"Utah.jpg",
"Hawaii.jpg"
)
)
)
);
$pathStrings = [
''site//projects//terrace_and_balcony//mexico.jpg'',
''site//projects//terrace_and_balcony//new_york.jpg'',
''site//projects//terrace_and_balcony//berlin.jpg'',
''site//projects//terrace_and_balcony//Kentucky.jpg'',
''site//projects//terrace_and_balcony//Utah.jpg'',
''site//projects//terrace_and_balcony//Hawaii.jpg'',
''site//projects//private_gardens//mexico.jpg'',
''site//projects//private_gardens//new_york.jpg'',
''site//projects//private_gardens//berlin.jpg'',
''site//projects//private_gardens//Kentucky.jpg'',
''site//projects//private_gardens//Utah.jpg'',
''site//projects//private_gardens//Hawaii.jpg''
];
$paths = [];
foreach ($pathStrings as $pathString) {
// Split by the delimiter.
$pathParts = explode(''//', $pathString);
// Build a nested assoc array representing the path.
// Each key and value comes from the delimited parts of the string.
// eg: site/projects/terrace_and_balcony/mexico.jpg
// becomes: [
// ''site'' => [
// ''projects'' => [
// ''terrace_and_balcony'' => [
// ''mexico.jpg''
// ]
// ]
// ]
// ]
$path = [array_pop($pathParts)];
foreach (array_reverse($pathParts) as $pathPart) {
$path = [$pathPart => $path];
}
// Add it to a temp list.
$paths[] = $path;
}
// Now, merge all the paths together recursively at once.
$tree = call_user_func_array(''array_merge_recursive'', $paths);
// Done.
print_r($tree);
Demostración: http://sandbox.onlinephpfunctions.com/code/12c82c18625dda23682baac37b2a5a8310fb869d