phparraysmultidimensional-arraygroupinghierarchical-data

Convert a flat array of space-delimited words into a multidimensional associative array using words as path keys terminating at empty arrays


I am trying to sort the following arrays.

Array(s)

$fruits = array(
    'mango',
    'mango red',
    'mango yellow',
    'orange',
    'banana',
    'apple',
    'apple red',
    'apple green',
);

What I have done:

$data = array_flip( $fruits ); // flip array
$data = array_fill_keys( array_keys( array_flip( $data ) ), 'array(),' ); // fill array value: "array(),"

print_r( $data );

I want this result:

$fruits = array(
    'mango'      => array(
        'red'       => array(),
        'yellow'    => array(),
    ),
    'orange'    => array(),
    'banana'    => array(),
    'apple'     => array(
        'red'       => array(),
        'green'     => array(),
    ),
);

Does anybody know how to do this?


Solution

  • Loop through the array, and split the string. Then recursively create nested arrays.

    $result = array();
    foreach ($fruits as $f) {
        $f_array = explode(' ', $f);
        $start = &$result;
        foreach ($f_array as $word) {
            if (!isset($start[$word])) {
                $start[$word] = array();
            }
            $start = &$start[$word];
        }
    }
    var_dump($result);
    

    DEMO