2

I can't seem to figure out the best way to do this. I have a RecursiveIteratorIterator.

$info = new RecursiveIteratorIterator(
    new GroupIterator($X), # This is a class that implements RecursiveIterator
    RecursiveIteratorIterator::SELF_FIRST
);

Note: GroupIterator is a class that handles our custom formatted data

When I loop through it, I get exactly what I expect.

foreach($info as $data){
    echo $info->getDepth().'-'.$data."\n";
}

The output is:

0-a
1-b
2-c
2-d
1-e
2-f
0-g
1-h
2-i

This is correct, so far. Now, what I want is to flatten the parents and children into a single array. I want one row for each max-depth child. The output I am trying to get is:

0-a 1-b 2-c
0-a 1-b 2-d
0-a 1-e 2-f
0-g 1-h 2-i

I can't figure out how to do this. Each iteration over the loop gives me another row, how can I combine the rows together that I want?

4

2 回答 2

1

我设法弄清楚了。 @ComFreek 为我指明了正确的方向。我没有使用计数器,而是使用当前深度来检查何时击中最低的孩子,然后将数据添加到最终数组中,否则我将其添加到临时数组中。

$finalArray = array();
$maxDepth = 2;
foreach($info as $data){
    $currentDepth = $info->getDepth();

    // Reset values for next parent
    if($currentDepth === 0){
        $currentRow = array();
    }

    // Add values for this depth
    $currentRow[$currentDepth] = $data;

    // When at lowest child, add to final array
    if($currentDepth === $maxDepth){
        $finalArray[] = $currentRow;
    }
}
于 2013-10-09T18:38:20.690 回答
0

尝试添加一个计数器变量:

// rowNr loops through 0, 1, 2
$rowNr = 0;
$curData = [];
$outputData = [];

foreach($info as $data){
  // got last element, add the temp data to the actual array
  // and reset temp array and counter
  if ($rowNr == 2) {
    $outputData[] = $curData;
    $curData = [];
    $rowNr == 0;
  }
  else {
    // save temp data
    $curData[] = $info->getDepth() . '-' . $data;
  }
  $rowNr++;
}
于 2013-10-09T16:21:45.700 回答