PHP Convert Single Dimensional Array to Two Dimensional


/ Published in: PHP
Save to your folder(s)

Function to convert a one dimensional array to two dimensional with option to specify how many columns. Returns two dimensional array on success or false on fail.


Copy this code and paste it in your HTML
  1. <?php
  2. $test = array(1,2,3,4,5,6,7,8,9);
  3.  
  4. function array_2d($array, $col_count=2){
  5. $result = false;
  6. if(!empty($array) && is_array($array)){
  7. $row_count = ceil( count($array) / $col_count);
  8. $pointer = 0;
  9. for($row=0; $row < $row_count; $row++) {
  10. for($col=0; $col < $col_count; ++$col){
  11. if(isset($array[$pointer])) {
  12. $result[$row][$col] = $array[$pointer];
  13. $pointer++;
  14. }
  15. }
  16. }
  17. }
  18. return $result;
  19. }
  20. $result = array_2d($test, 3);
  21. echo '<pre>'.print_r($result, 1).'</pre>';
  22. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.