Generating a parent child array based on URL
I 开发者_开发百科have the following url /dir1/dir2/page.php
I need to generate a an array of the parent->child relation form the above url.
/dir1
|
|
/dir2/
|
|
page.php
eg :
array('dir1'=> array(
'child' => array( 'dir2' => array(
'child' => array(
'page' => array())))));
I tried using the recursive function but not able to figure out the logic. Please let me know if you need some more explanation.
Here's a recursive method (sorry for lack of comments, it's late):
<?php
$urls = array('/dir1/dir2/page.php', '/dir1/dir3/page');
function url_to_array($url, $array=null) {
if($array === null) {
$array = array();
$url_parts = explode('/', $url);
return url_to_array($url_parts, $array);
} else {
if(count($url)) {
$item = array_pop($url);
if($item) {
if(!$array) {
$array = array('page' => $array);
} else {
$array = array($item => array('child' => $array));
}
}
return url_to_array($url, $array);
} else {
return $array;
}
}
}
$array = array();
foreach($urls as $url) {
$array = array_merge_recursive($array, url_to_array($url));
}
print_r($array);
?>
It prints out:
wraith:Downloads mwilliamson$ php recursive.php
Array
(
[dir1] => Array
(
[child] => Array
(
[dir2] => Array
(
[child] => Array
(
[page] => Array
(
)
)
)
[dir3] => Array
(
[child] => Array
(
[page] => Array
(
)
)
)
)
)
)
Here's a copy/paste from a forum, so I don't know that it works (I skimmed it, and it looks legit).
function getDirectory($path = '.', $ignore = '')
{
$dirTree = array();
$dirTreeTemp = array();
$ignore[] = '.';
$ignore[] = '..';
$dh = opendir($path);
while (false !== ($file = readdir($dh)))
{
if (!in_array($file, $ignore))
{
if (!is_dir("$path/$file"))
{
$dirTree["$path"][] = $file;
} else {
$dirTreeTemp = getDirectory("$path/$file", $ignore);
if (is_array($dirTreeTemp))
{
$dirTree = array_merge($dirTree, $dirTreeTemp);
}
}
}
}
closedir($dh);
return $dirTree;
}
Here is an actual solution that I wrote specifically for this problem. No recursion involved!
This returns the exact same array as you posted in your question.
function recursiveArrayFromURL () {
$parts = array_slice(explode("/", $_SERVER['REQUEST_URI']), 1);
$refs = array();
foreach($parts as $key => $v) {
// remove extension from last file
if($key == count($parts) - 1) $v = substr($v, 0, -4);
$thisref = &$refs[$v];
if(is_null($thisref)) $thisref = array();
$parent = end(array_slice($parts, 0, $key - 1));
if(!array_key_exists("child", $refs[$parent])) $refs[$parent]['child'] = array();
$refs[$parent]['child'][ $v ] = $thisref;
}
return array_slice($refs, 0, 1);
}
精彩评论