Tuesday, 28 August 2018

Create a multidimensional array from a table

I am trying to create a multidimensional array from a linear array.

This array:
$array = array(
    array('level-one', 'level-two', 'level-three'),
    array('level-one', 'level-two', 'level-three', 'level-four'),
    array('level-one', 'level-two', 'level-three', 'level-four', 'item 1'),
    array('level-one', 'level-two', 'level-three', 'level-four', 'item 2'),
    array('level-one', 'level-two', 'level-three', 'level-four', 'item 3'),
    array('level-one', 'level-two', 'level-three', 'level-four', 'item 4'),
);

Into:
$multi = array(
    'level-one' => array(
        'level-two' => array(
            'level-three' => array(
                'level-four' => array(
                    'item 1',
                    'item 2',
                    'item 3',
                    'item 4',
                )
            )
        )
    )
);

I guess I should go somehow recursive but I can't find a recursive solution logic.

You can give this a go
function to_nested($ary){
    $a = array();
    foreach ( $ary as $rec ){
        $b = &$a;
        $node = null;
        foreach ( $rec as $f ){
            if ( $node !== null ){
                if ( !isset($b[$node]) ){
                    $isleaf = array_search($node,$b);
                    if ( $isleaf !== false )
                        unset($b[$isleaf]);
                    $b[$node] = array();
                }
                $b = &$b[$node];
            }
            $node = $f;
        }
        //push leaf
        if ( empty($b) ){
            $b = array();
        }
        array_push($b, $f);
    }

    return $a;
}

$array = array(
    array('level-one', 'level-two', 'level-three'),
    array('level-one', 'level-two', 'level-three', 'level-four'),
    array('level-one', 'level-two', 'level-three', 'level-four', 'item 1'),
    array('level-one', 'level-two', 'level-three', 'level-four', 'item 2'),
    array('level-one', 'level-two', 'level-three', 'level-four', 'item 3'),
    array('level-one', 'level-two', 'level-three', 'level-four', 'item 4'),
);

print_r(to_nested($array));

result:
Array (
    [level-one] => Array
        (
            [level-two] => Array
                (
                    [level-three] => Array
                        (
                            [level-four] => Array
                                (
                                    [0] => item 1
                                    [1] => item 2
                                    [2] => item 3
                                    [3] => item 4
                                )
                        )
                )
        )
)

I'm not sure what the rules are for your input array so I'd suggest that you play around with different valid inputs to see if the results of this function work for you.

0 comments:

Post a Comment