phparraysnestedkeypaths

Convert flat array representing a key path into a nested array terminating at an empty array


How to convert my array:

Array
(
    [0] => Apple
    [1] => Orange
    [2] => Tomato
)

To this:

Array
(
    [Apple] => Array
        (
            [Orange] => Array
                (
                    [Tomato] => Array()
                )

        )

)

I do not know how many elements will be in my array.


Solution

  • Output

    Array
    (
        [0] => Apple
        [1] => Orange
        [2] => Tomato
        [3] => Banana
        [4] => Papaya
    )
    Array
    (
        [Apple] => Array
            (
                [Orange] => Array
                    (
                        [Tomato] => Array
                            (
                                [Banana] => Array
                                    (
                                        [Papaya] => Array
                                            (
                                            )
    
                                    )
    
                            )
    
                    )
    
            )
    
    )
    

    Code

    $fruits = [
    
      "Apple",
      "Orange",
      "Tomato",
      "Banana",
      "Papaya"
    
    ];
    
    // Result Array
    
    $result = [
    
      $fruits[count($fruits) - 1] => []
    
    ];
    
    // Process
    
    for ($counter = count($fruits) - 2; $counter >= 0; $counter--) {
    
      $temp = $result;
    
      unset($result);
    
      $result[$fruits[$counter]] = $temp;
    
    }
    
    // Display
    
    echo "<pre>".print_r($fruits, true)."</pre>";
    echo "<pre>".print_r($result, true)."</pre>";