Jump to content

Implement array_chunk()


Sinmok
 Share

Recommended Posts

Don't know if you can already do this, but implementing PHPs array_chunk method would be pretty useful..

For example

$list = $pages->find("template=something"); // Returns 5 pages

$chunked = $list->chunk(3);

print_r($chunked);

/*prints*/

array(
  0=> array(
             Page,
             Page,
             Page
         )
  1=> array(
             Page,
             Page
         )
)

Especially useful if you're trying to print pages into columns.

Can you already do this?

  • Like 4
Link to comment
Share on other sites

This looks similar to (but a little simpler than) pagination to me. Have you tried a straight pagination solution to this?

Otherwise, something like this might do if you don't need access to the $page objects themselves...

$list = $pages->find('whatever');

$titles = array();
foreach ($list as $p) {
    $titles[] = $p->title;
}

$chunked = array_chunk($titles, 3);

print_r($chunked);

Even simpler, plus you get access to the object with all its data;

$list = $pages->find('whatever');
$chunked = array_chunk($list->getArray(), 3);

// Output plaintext titles by iterating over chunks and pages in chunks.
// Access protected fields as needed using $page->fieldname and format as required.
foreach ($chunked as $i => $chunk) {
    echo "Chunk $i\n";
    foreach ($chunk as $page) {
        echo $page->title, "\n";
    }
}
Edited by netcarver
Updated second example to show how to access fields.
  • Like 5
Link to comment
Share on other sites

Thanks Sinmok and netcarver. It would be really useful when we are using a front-end framework like Bootstrap. 

<?php 
 $list = $pages->find("template=basic-page"); // Returns 5 pages
 $chunked = array_chunk($list->getArray(), 3);
?>

<?php foreach($chunked as $i => $row): ?>
  <div class='row'>
  <?php foreach($row as $item) : ?>
    <div class="col-md-4">
      <?php echo $item->title; ?>    
    </div>                            
  <?php endforeach; ?>    
</div>
<?php endforeach; ?>                    
  • Like 8
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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...