0

The result of a query in my database returns something like this (a record for each row):

1.
1.1.
1.1.01.
1.1.01.001
1.2.
1.2.01.
1.2.02.

I'm trying to create something that returns me a multidimensional array in a tree format, like this:

array(
    '1.' => array(
        '1.1' => array(
            '1.1.01.' => array(
                (int) 0 => '1.1.01.001'
            )
        ),
        '1.2' => array(
            (int) 0 => '1.2.01.',
            (int) 1 => '1.2.02.'
        )
    )
)

All I could think to do was reverse the order of elements using explode().

I appreciate any suggestions.

4
  • 1
    You'll get your result in an array. Take that array and loop through it and switch places/create new arrays inside it. Commented Feb 25, 2013 at 15:07
  • 1
    What is wrong with the reverse the order of elements using explode ??? seems to work Commented Feb 25, 2013 at 15:08
  • I think this answer would help you: Create Multidimensional array from text lines Commented Feb 25, 2013 at 15:11
  • @GeorgeViolaris its totally different .. not the final value has combination of all the keys Commented Feb 25, 2013 at 15:12

1 Answer 1

2

Your format is very tricky because of :

1.2.
1.2.01.     |
1.2.02.     V  Making this array instead of value 

You can try

$string = "1.
1.1.
1.1.01.
1.1.01.001
1.2.
1.2.01.
1.2.02.";

$array = explode("\n", $string);
$data = array();
$temp = &$data;

$it = new CachingIterator(new ArrayIterator($array), CachingIterator::FULL_CACHE);
$continue = false;
foreach ( $it as $v ) {
    $v = trim($v);
    if ($it->hasNext()) {
        $next = trim($it->getInnerIterator()->current());
        if (stripos($next, $v) === 0) {
            $temp = &$temp[$v];
        } else {
            $temp[] = $v;
            if (strlen($next) != strlen($v)) {
                $temp = &$data;
            }
        }
    } else {
        $temp[] = $v;
    }
}
print_r($data);

Output

Array
(
    [1.] => Array
        (
            [1.1.] => Array
                (
                    [1.1.01.] => Array
                        (
                            [0] => 1.1.01.001
                        )

                )

        )

    [1.2.] => Array
        (
            [0] => 1.2.01.
            [1] => 1.2.02.
        )

)

Here is a move COMPLEX demo

Sign up to request clarification or add additional context in comments.

1 Comment

Almost, because item 1.2 need to stay at the same level of 1.1. Item 1 has 1.1 and 1.2, item 1.1 has 1.1.01 and so on. I'll try to modify your solution, thanks anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.