K
K
Kim_Soal2018-02-02 13:34:38
PHP
Kim_Soal, 2018-02-02 13:34:38

Nesting array elements?

There is a one-dimensional array of the form

[0] => dir2
[1] => dir2_1
[2] => dir2_1_1
...

There may be one element, or there may be many.
How at the output to get them nested in each other in this way?
array(
  "dir2"=>array(
    "dir2_1"=>array(
      "dir2_1_1"=>array(...)
    )
  )
)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Cat Anton, 2018-02-02
@Kim_Soal

Can be recursed: https://3v4l.org/m5Cup

<?php

$input = ['dir2', 'dir2_1', 'dir2_1_1'];

function convert_array(array $input, array $output = []) {
    if (empty($input)) {
        return $output;
    }
    
    $value = array_pop($input);
    
    return convert_array($input, [$value => $output]);
}

var_dump(convert_array($input));

It is possible without recursion: https://3v4l.org/4FuZ4
<?php

$input = ['dir2', 'dir2_1', 'dir2_1_1'];

$output = [];
foreach (array_reverse($input) as $value) {
    $output = [$value => $output];
}

var_dump($output);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question