-
Notifications
You must be signed in to change notification settings - Fork 44
Getting Started: 6. Iterating And Filtering
Iterations can be performed without interrupting the fluent flow.
iterates the current context (after a query or an add/append/prepend operation).
$book->query('//chapter')
->each(function($i, $domnode) {
$this->attr('id', $i + 1);
echo $domnode->nodeValue;
});
ProTip:
Any valid callable is accepted, not only closures.function setattr($chapter, $i, $domnode) { $chapter->attr('id', $i + 1); echo $domnode->nodeValue; } $book->query('//chapter') ->each('setattr');
maps the current context (after a query or an add/append/prepend operation).
$results = $book->query('//chapter')->map(function($i, $domnode) {
return $domnode->getAttribute('id');
});
ProTip:
Any valid callable is accepted, not only closures.function mapNode($ctx, $i, $domnode) { return $domnode->getAttribute('id'); } $results = $book->query('//chapter')->map('mapNode');
repeats the following method call $n
times.
$book->query('//chapters')
->times(2)
->add('chapter');
If a callable is passed as second argument, the callable is called $n
times.
$book->query('//chapters')
->times(2, function($i) {
$this->add('chapter', [ 'id' => $i + 5 ]);
});
ProTip:
Any valid callable is accepted, not only closures.function addchapter($chapters, $i) { $chapters->add('chapter', [ 'id' => $i + 5 ]); } $book->query('//chapters') ->times(2, 'addchapter');
filters programmatically the current context (after a query or an add/append/prepend operation).
$book->query('//chapters')
->filter(function($i, $node) {
return $i % 2 === 0;
})
->attr('even');
A false
return value informs ->filter()
to expunge that particular element from the fluent context.
ProTip:
Any valid callable is accepted, not only closures.function filtereven($chapter, $i, $node) { return $i % 2 === 0; } $book->query('//chapters') ->filter('filtereven') ->attr('even');