0

I want o sort a multidimensional array (which I don't know the length) and keep the index strings. The data of this multidimensional array is from a directory which can have unlimited folders & files.

I have successfully grabbed the folder structure into an array using this List all the files and folders in a Directory with PHP recursive function and I can sort the array with a recursive function like this https://stackoverflow.com/a/4501406/3355243.

Problem

When sorting, all the array indexs are replaced with numbers. I'd like to keep the array index as strings because it holds the folder name.

Input

Folder A => Array
(
    file.php,
    file1.php,
    Folder B => Array 
    (
        file.php,
        file1.php, 
        Folder A => Array 
        (
            file.php,
            file1.php, 
        )
        something.php
    ),
    something.php
),
Folder B => Array 
(
    other.php,
    other2.php 
),
Folder C => Array 
(
    Folder A => Array 
    (
        a.php,
        b.php
    ),
    something.php
)

Expected output

Folder A => Array
(
    file.php,
    file1.php,
    something.php,
    Folder B => Array 
    (
        file.php,
        file1.php, 
        something.php,
        Folder A => Array 
        (
            file.php,
            file1.php, 
        )       
    ),  
),
Folder B => Array 
(
    other.php,
    other2.php 
),
Folder C => Array 
(
    something.php
    Folder A => Array 
    (
        a.php,
        b.php
    ),  
)

Current output

0 => Array
(
    file.php,
    file1.php,
    something.php,
    0 => Array 
    (
        file.php,
        file1.php, 
        something.php,
        0 => Array 
        (
            file.php,
            file1.php, 
        )       
    ),  
),
1 => Array 
(
    other.php,
    other2.php 
),
2 => Array 
(
    something.php
    0 => Array 
    (
        a.php,
        b.php
    ),  
)

Final goal

To show the array / folder structure into a select box with Groups & Options.

enter image description here

Linesofcode
  • 5,327
  • 13
  • 62
  • 116
  • 1
    And your attempt at resolving this failed where? – El_Vanja Apr 26 '21 at 11:16
  • @El_Vanja in the recursive function in the link that I posted. – Linesofcode Apr 26 '21 at 11:18
  • 1
    I understand that the function you're using isn't producing the result you want. I'm asking about your own efforts to try and modify this function or perhaps devising your own function based on the ideas provided in similar topics such as that one. – El_Vanja Apr 26 '21 at 11:22

1 Answers1

0

Solved.

The solution of the link Order multidimensional array recursively at each level in PHP uses ksort to order the array and the solution, in my case, I had to use the asort.

https://www.php.net/manual/en/function.asort.php

asort — Sort an array and maintain index association

Linesofcode
  • 5,327
  • 13
  • 62
  • 116