N
N
Nikita Kolesnikov2020-05-18 01:40:18
PHP
Nikita Kolesnikov, 2020-05-18 01:40:18

How to split path into arrays like file/folder + parent folder?

It is necessary to split the file path into an array with arrays containing two values: the file/folder name and the child folder name.
For example, there is a path /dir1/dir2/file.txt , it needs to be split so that the output is something like this:

array(3) {
  [0]=>
  array(2) {
    ["file_name"]=>
    string(4) "dir1"
    ["parent_file"]=>
    string(0) ""
  }
  [1]=>
  array(2) {
    ["file_name"]=>
    string(4) "dir2"
    ["parent_file"]=>
    string(4) "dir1"
  }
  [2]=>
  array(2) {
    ["file_name"]=>
    string(8) "file.txt"
    ["parent_file"]=>
    string(4) "dir2"
  }
}


What is the least hacky way to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Sarvarov, 2020-05-18
@NikitOS_MV

function extractPathElements(string $path): array
{
    $explodedPath = explode('/', $path);

    $pathTree = [];
    
    foreach ($explodedPath as $key => $value) {
        if (!$value) {
            continue;
        }
        
        $pathTree[] = [
            'file_name' => $value, 
            'parent_file' => $explodedPath[$key-1] ?? '', 
        ];
    }
    
    return $pathTree;
}

// client code
var_dump(extractPathElements('/dir1/dir2/file.txt'));

/*
array(3) {
  [0]=>
  array(2) {
    ["file_name"]=>
    string(4) "dir1"
    ["parent_file"]=>
    string(0) ""
  }
  [1]=>
  array(2) {
    ["file_name"]=>
    string(4) "dir2"
    ["parent_file"]=>
    string(4) "dir1"
  }
  [2]=>
  array(2) {
    ["file_name"]=>
    string(8) "file.txt"
    ["parent_file"]=>
    string(4) "dir2"
  }
}
*/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question