how to merge multiple url/path into multidimensional array?
I have array like this:
$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] => sit开发者_开发知识库e\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
)
How to convert it to that:
$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);
Demo: http://sandbox.onlinephpfunctions.com/code/12c82c18625dda23682baac37b2a5a8310fb869d
精彩评论