so if I have a string like this, e.g. "/path1/folder/fun/yay/"
How can I run that through a function to return an array of all the parent paths, looking like this:
array (
'/',
'/path1/',
'/path1/folder/',
'/path1/folder/fun/',
'/path1/folder/fun/yay/'
)
This is what I have so far, obviously it doesn't work and it's confusing to say the least...
$a = explode('/',$path); $ii = 0; $path_array = array();
for ($i = 0; $i < sizeof($a); $i++) {
if ($a[$i]) {
$path_array[$ii] = "";
for ($n = 0; $n < $i; $n++)
{
$path_array[$ii] .= $a[$n];
}
$ii++;
}
}
file_put_contents('text.txt',serialize($path_array));
Thanks!
BTW my end goal here is to be able to run an SQL query on a table of folder paths to increment a value on a folder and all of its parents.
Maybe there's some sort of SQL operator where I could select all rows whose path is a part of the path I input? Kinda like this in reverse:
mysqli_query($mysqli,'UPDATE content_folders SET size = size+'.filesize("content/$id").' WHERE path LIKE "'.$path.'%"')
As for the PHP function - something like this would work:
function returnAllPaths ( $fullPath = '/' , Array $pathHistory = array() )
{
while ( strlen($fullPath) > 1 AND $fullPath[0] === '/' )
{
array_push($pathHistory, $fullPath);
$fullPath = preg_replace('%(.*/)[^/]+(?:/)?$%is', '$1', $fullPath);
}
array_push($pathHistory, $fullPath);
return array_reverse($pathHistory);
}
You can use this
$path = '/path1/folder/fun/yay/';
$path = explode('/',$path);
$path = array_filter($path);
$iniVal = '';
$array_paths = array();
array_push($array_paths,'/');
foreach($path as $array){
$value = $iniVal.'/'.$array.'/';
array_push($array_paths,$value);
$iniVal .= '/'.$array;
}
//print_r($array_paths);
Output would display in array such as :
Array ( [0] => / [1] => /path1/ [2] => /path1/folder/ [3] => /path1/folder/fun/ [4] => /path1/folder/fun/yay/ )
same as
array (
'/',
'/path1/',
'/path1/folder/',
'/path1/folder/fun/',
'/path1/folder/fun/yay/'
)
DEMO : PHP FIDDLE