My problem is very similar to the one described here in this topic Create nested list from PHP array for dropdown select field The problem is that if investments are not consecu
It does not work because you are not setting the "parent" attribute right. Even if the name is "Test 2.1", using this algorithm, you have to set the parent index. If you change your array to this, it'll work:
$rows = array(
array ('id' => 1, 'name' => 'Test 1', 'parent' => 0),
array ('id' => 2, 'name' => 'Test 1.1', 'parent' => 1),
array ('id' => 3, 'name' => 'Test 1.2', 'parent' => 1),
array ('id' => 4, 'name' => 'Test 1.2.1', 'parent' => 3),
array ('id' => 5, 'name' => 'Test 1.2.2', 'parent' => 3),
array ('id' => 6, 'name' => 'Test 1.2.2.1', 'parent' => 5),
array ('id' => 7, 'name' => 'Test 2', 'parent' => 0),
array ('id' => 8, 'name' => 'Test 2.1', 'parent' => 7),
array ('id' => 9, 'name' => 'another data with no parent', 'parent' => 0),
);