Search code examples
phparraysarray-flip

Dealing with array PHP


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?

Hope you can understand the question. Thank you in advance.


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