Jump to content

array_chunk support


SwimToWin
 Share

Recommended Posts

While ProcessWire and WireArray does not have support for array_chunk, there is a simple way to achieve this.

With array_chunk() you can easily add DIVs to a foreach loop, without having to set up counters when using general PHP (hat-tip to Laurance over at StackOverflow). The idea in a ProcessWire context is to use array_chunk() to split an array into chunks - and use eq() when looping page results.

Simple example that will split a WireArray into three columns. Before we begin, you should know the array_chunk syntax: array_chunk($array, $chunk_size, $preserve_keys=true|false).

<?php
$p = $pages->get('/news')->children('limit=15, template=article, sort=-sort');
?>
<div class="row">
	<?php foreach (array_chunk(range(0,14),5) as $chunk): ?>
	<div class="col">
		<?php foreach ($chunk as $i): ?>
			<h5><a href="<?=$p->eq($i)->url?>"><?=$p->eq($i)->title?></a></h5>
		<?php endforeach; ?>
	</div>
	<?php endforeach; ?>
</div>

A more realistic example:

<?php
$p = $pages->get('/news');
$pp = $p->children('limit=15, template=article, sort=-sort');
?>
<h2><a href="<?=$p->url?>"><?=$p->title?></a></h2>
<div class="row">
	<?php foreach (array_chunk(range(0,14),5) as $chunk): ?>
	<div class="col">
		<?php foreach ($chunk as $i): ?>
			<h5>
				<a href="<?=$pp->eq($i)->url?>"><?=$pp->eq($i)->title?></a>
			</h5>
		<?php endforeach; ?>
	</div>
	<?php endforeach; ?>
</div>
  • Like 3
Link to comment
Share on other sites

Although your approach would be a bit faster (less function calls overall), it can be turned into a hook and be called on any class that extends WireArray, basically any collection returned by ProcessWire API

// /site/ready.php

wire()->addHookMethod('WireArray::chunk', function (HookEvent $e) {
    $chunkSize = (int)$e->arguments(0) ?? 1;
    $e->return = array_chunk($e->object->getArray(), $chunkSize);
});

A common use case is to build grids

<?php $myPages = $pages('template=my-template'); ?>
<div class="grid">
<?php foreach ($myPages->chunk(5) as $chunk): ?>
    <div class="row">
        <?php foreach ($chunk as $item): ?>
            <div class="col"><?= $item->title ?></div>
        <?php endforeach; ?>
    </div>
<?php endforeach; ?>
</div>

 

  • Like 5
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...