I'm using the following functions to convert a tabbed list to array, but tabs with depth of 1 are added to array[1];
The tab list:
$test = "Test
Sub Item Test 1 (Test)
Sub Item Test 2 (Test)
Sub Sub Item Test 1 (Sub Item Test 2)
Sub Sub Sub Item Test 1 (Sub Item Test 2)
Test 2
Sub Item Test 1 (Test 2)
Test 3
Sub Item Test 1 (Test 3)
Test 4
Sub Item Test 1 (Test 4)
Test 5
Sub Item Test 1 (Test 5)";
The functions:
function convert( $list, $indent = "\t" ) {
$main = array();
foreach ( explode( PHP_EOL, $list ) as $line ) {
$depth = substr_count( $line, $indent );
$line = trim( $line );
if ( $line == '' ) {
continue;
}
$a = &buildArray( $main, $depth, 0, $line );
$a[$i++] = $line;
}
return $main;
}
function &buildArray( &$array, $depth, $current = 0, $line = null ) {
if ( $depth == $current ) {
return $array;
} else {
foreach ( $array as &$value ) {
if ( is_array( $value ) ) {
return buildArray( $value, $depth, ++ $current );
}
}
$tmp = array();
$array[] = &$tmp;
return buildArray( $tmp, $depth, ++ $current );
}
}
Here is the result after running "convert($test)"
Array
(
[0] => Test
[1] => Array
(
[1] => Sub Item Test 1 (Test)
[2] => Sub Item Test 2 (Test)
[3] => Array
(
[0] => Array
(
[3] => Sub Sub Item Test 1 (Sub Item Test 2)
)
[4] => Sub Sub Sub Item Test 1 (Sub Item Test 2)
)
[6] => Sub Item Test 1 (Test 2)
[8] => Sub Item Test 1 (Test 3)
[10] => Sub Item Test 1 (Test 4)
[12] => Sub Item Test 1 (Test 5)
)
[5] => Test 2
[7] => Test 3
[9] => Test 4
[11] => Test 5
)
So why do I get array[1][6] instead of array[6], and so on for all the lines after array[5]?