Posted By

buzzswarbrick on 06/04/14


Tagged

php


Versions (?)

Multi Dimensional Array into Rows


 / Published in: PHP
 

Convert array into rows

Really handy for a clean way to insert tags per (n) amount of items

eg. http://stackoverflow.com/questions/8753786/php-adding-divs-to-a-foreach-loop-every-4-times

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

[1] => Array ( [0] => 4 [1] => 5 [2] => 6 ) [2] => Array ( [0] => 7 [1] => 8 [2] => 9 ) )
  1. function array_to_rows($array, $itemsPerRow = 7){
  2. $counter = 0;
  3. $row_array = array();
  4. $row = array();
  5. foreach($array as $item) {
  6. if($counter > $itemsPerRow-1) {
  7. $row_array[] = $row;
  8. $row = array();
  9. $counter = 0;
  10. }
  11. //if array is smaller than minimum pump them into the first row
  12. if(count($array) < $itemsPerRow) {
  13. $row_array[0][] = $item;
  14. }
  15. $row[] = $item;
  16. $counter++;
  17. }
  18. $result = call_user_func_array('array_merge', $row_array); //flatten multidimensional array
  19. $lastRow = array_slice($array, count($result), count($array));
  20. if(count($lastRow)) {
  21. $row_array[] = $lastRow;
  22. }
  23. return $row_array;
  24. }

Report this snippet  

You need to login to post a comment.