Domanda

I scorrere un array multidimensionale con RecursiveIteratorIterator e vorrei essere in grado di sapere se l'elemento corrente è l'ultimo figlio di esso di profondità. Ho pensato a questo:

$iterator = new RecursiveIteratorIterator($array,
  RecursiveIteratorIterator::SELF_FIRST);    
foreach ($iterator as $val) {
  $next = clone $iterator;
  $next->next();
  $lastChild = ($next->getDepth() < $iterator->getDepth());
}

Ma la RecursiveIteratorIterator dice che non è clonabile.

È stato utile?

Soluzione

La frase "ultimo figlio della sua profondità" non è particolarmente chiaro. Potrebbe illustrare con precisione cosa si intende; la destinazione d'uso per questo?

Se vuoi dire, molto semplicemente, che la profondità cambierà dopo l'elemento corrente, quindi il (Recursive)CachingIterator ha un metodo hasNext utile per determinare se l'iteratore ha ulteriori elementi. Per fare un esempio annacquata simile a quella domanda:

$array  = array(
    range(1,6),
    range(7,8),
    'foo' => range(1,3),
    'bar' => range(4,5),
);

$rit = new RecursiveArrayIterator($array);
$iterator = new RecursiveIteratorIterator(
    new RecursiveCachingIterator($rit),
    RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $val) {
    $lastChild = !$iterator->hasNext();
    if ($lastChild) {
        echo "$val is the last child!\n";
    }
}

Uscite:

6 is the last child!
8 is the last child!
3 is the last child!
5 is the last child!
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top