Skip to content
Devin Smith edited this page Feb 3, 2016 · 10 revisions

Looper provides an interface similar to Iterator with some Resource specific features.


Methods

each

Looper allows the use of $loop->each(), foreach ($loop as $item), or while($loop->valid() interchangeably.

foreach ($loop as $item) {
	//item
}

or

$loop->each(function() {
	// $this
});

or

while ($loop->valid()) {
	// $loop->current()
	$loop->next();
}
get

Get grabs an item in the loop by index.

$loop->get(0);
json

Looper allows the use of $loop->json() or json_encode($loop) interchangeably.

echo $loop->json();

or

echo json_encode($loop);
set

Set properties of all items in a loop

$loop = new \Tipsy\Looper([
	(object)['a' => 1],
	(object)['a' => 1],
	(object)['a' => 2]
]);
$loop = $loop->set('a', 1);
echo $loop->json(); // returns 3 items with a set to 1
filter

Filtering a Loop will return all objects who's properties match the properties of a passed argument.

$loop = new \Tipsy\Looper([
	(object)['a' => 1],
	(object)['a' => 1],
	(object)['a' => 2]
]);
$loop = $loop->filter([
	'a' => 1
]);
echo $loop->json(); // returns the first 2 items as json
not

Not works the same as filter except backwards

$loop = new \Tipsy\Looper([
	(object)['a' => 1],
	(object)['a' => 1],
	(object)['a' => 2]
]);
$loop = $loop->not([
	'a' => 1
]);
echo $loop->json(); // returns the last item in json
slice

Slice works similar to array_slice

$loop = new \Tipsy\Looper([
	(object)['a' => 1],
	(object)['a' => 1],
	(object)['a' => 2]
]);
$loop = $loop->slice(1, 2);
echo $loop->json(); // returns the last 2 items in json
parent

When nesting loops, parent returns the immediate parent loop. This is most useful when using filters

$loop = new \Tipsy\Looper([
	(object)['a' => 1],
	(object)['a' => 1],
	(object)['a' => 2]
]);
$loop = $loop->filter(['a' => 1])->set('a', 2)->parent();
echo $loop->json(); // returns a list of 3 items with a set to 2

Advanced Usage

You can see some more advanced examples in tests/LooperTest.php.