Using PHP 5.2, I'm trying to parse an arbitrary number of path/directory strings into an array, such that they can be processed breadth-first. This is to allow me to script a sparse checkout from a Subversion repository, telescoping the indicated paths. All the paths on the same level have to be specified in the same svn update --depth empty statement.
I get the desired output, but I wonder if there's a cleaner way to do this. (And, yes, I know there are changes needed for efficiency.)
EDIT I modified the original post to handle cases of multiple children in the same parent. My revised code is
$main = array(
'a/b/c1/',
'a/b/c2/d/e1',
'a/b/c2/d/e2',
'A/B/',
'alpha/beta/gamma/delta/epsilon'
);
$splits = array();
$max = 0;
for ($i=0; $i<count($main); $i++) {
$splits[$i] = explode(DIRECTORY_SEPARATOR, trim($main[$i], DIRECTORY_SEPARATOR));
if (count($splits[$i]) > $max) {
$max = count($splits[$i]);
}
}
for ($i=0; $i<$max; $i++) {
$levels[$i] = array();
for ($path=0; $path<count($splits); $path++) {
if (array_key_exists($i, $splits[$path])) {
$levels[$i][] = implode(DIRECTORY_SEPARATOR, array_slice($splits[$path], 0, $i+1));
}
}
$levels[$i] = array_unique($levels[$i]);
sort($levels[$i]); // just to reset indices
}
This changes my output structure to the following, which both provides unique directories at each level and retains sibling nodes.
Array
(
[0] => Array
(
[0] => A
[1] => a
[2] => alpha
)
[1] => Array
(
[0] => A/B
[1] => a/b
[2] => alpha/beta
)
[2] => Array
(
[0] => a/b/c1
[1] => a/b/c2
[2] => alpha/beta/gamma
)
[3] => Array
(
[0] => a/b/c2/d
[1] => alpha/beta/gamma/delta
)
[4] => Array
(
[0] => a/b/c2/d/e1
[1] => a/b/c2/d/e2
[2] => alpha/beta/gamma/delta/epsilon
)
)
In my code, I then iterate over the final $levels array. Unfortunately, this still requires two iterations: one for depth empty and one for depth infinity, but I'm sure that could be worked out.
$count = count($levels);
for ($i=0; $i<$count; $i++) {
echo '<p>', 'svn update --set-depth empty ', implode(' ', $levels[$i]), "</p>\n";
}
$count = count($main);
for ($i=0; $i<$count; $i++) {
echo '<p>', 'svn update --set-depth infinity ', $main[$i], "</p>\n";
}
RecursiveDirectoryIteratorto implement it :-)