In PHP, how do I chunk objects with SPL?

The following example demonstrates how to chunk objects using the Standard PHP Library (SPL). SPL provides a convenient way to manage collections of objects. Here, we utilize `ArrayObject` and `SplFixedArray` to chunk objects effectively.

<?php // Create an ArrayObject of items $items = new ArrayObject([ (object) ['id' => 1, 'name' => 'Item 1'], (object) ['id' => 2, 'name' => 'Item 2'], (object) ['id' => 3, 'name' => 'Item 3'], (object) ['id' => 4, 'name' => 'Item 4'], (object) ['id' => 5, 'name' => 'Item 5'], (object) ['id' => 6, 'name' => 'Item 6'] ]); // Define the chunk size $chunkSize = 2; $chunks = new SplFixedArray(ceil($items->count() / $chunkSize)); // Split items into chunks for ($i = 0; $i < $items->count(); $i += $chunkSize) { $chunks[$i / $chunkSize] = $items->slice($i, $chunkSize); } // Display the chunks foreach ($chunks as $chunk) { echo "<div class='chunk'>"; foreach ($chunk as $item) { echo "<p>ID: {$item->id}, Name: {$item->name}</p>"; } echo "</div>"; } ?>

chunking objects PHP SPL ArrayObject SplFixedArray chunks object management