Indented text converted to arrays of arrays

From: Brad Baxter (bmb_at_ginger.libs.uga.edu)
Date: 06/29/04


Date: Tue, 29 Jun 2004 17:37:50 -0400

Greetings,

I would like to take a table of indented text like the following:

AAA
    BBB
    CCC
DDD
    EEE
        FFF
GGG

... and convert it into a nested array of arrays like the following:

[
[ 'AAA' => [
    'BBB',
    'CCC',
] ],
[ 'DDD' => [
    [ 'EEE' => [
        'FFF',
    ] ],
] ],
'GGG',
]

That is, if an element $a is an array ref, then $a->[0] is the text for
that level and $a->[1] is an array ref to the next level(s). Otherwise $a
is the text for that level.

The indenting is regular, the levels may be arbitrarily deep, and no
double indenting is allowed, i.e., the following is disallowed:

AAA
    BBB
CCC
        DDD

The solution I've come up with so far is to create the following literal
string and eval it:

[
[ 'AAA' => [
    [ 'BBB' => [
    ] ],
    [ 'CCC' => [
    ] ],
] ],
[ 'DDD' => [
    [ 'EEE' => [
        [ 'FFF' => [
        ] ],
    ] ],
] ],
[ 'GGG' => [
] ],
]

This obviously is not exactly what I describe above, but I can make it
work. However, this solution seems rather draconian, and I feel certain
there is a much simpler answer.

Regards,

Brad



Relevant Pages

  • Re: Finite $_POST loops infinitely - help!
    ... PHP Code: ... Perform an array scan ... Instead of indenting the whole function, you may wish to just add a ... this->data = phillip ...
    (comp.lang.php)
  • Re: help with recursive function
    ... I've upgraded PHP to version 5 and both your code and the old code on that website work beautifully. ... // output array structure for debugging ... SELECT id, parent, name ... // fetch the data into a nested array structure ...
    (comp.lang.php)
  • Re: Hash Sorting
    ... Ilan Berci wrote: ... hash of arrays into an array of arrays where the second arrays is ... my exact code that doesn't work: ... doing this I expect pi_array_sorted to be a nested array, sorted by key, ...
    (comp.lang.ruby)
  • sorting doesnt sort?
    ... I've got an array of arrays that I need to sort on preferably one of the ... indices of the nested array, keeping the order of the outside array. ... or use a numeric index thus making the ...
    (comp.lang.php)
  • Re: Cloning arrays
    ... puts "The ID of a is #" ... change the corresponding element of the other array (because they contain the ... If your array is a nested array, things become more complicated, as ... Marshalling - not enough time to keep up with the newsgroup. ...
    (comp.lang.ruby)