将动态数量的项目划分为列

时间:2010-12-08 17:59:25

标签: php pagination

我有一个动态数量的项目,我需要将其分成列。让我说我得到了这个:

array("one", "two", "three", "four", "five", "six", "seven", "eight")

我需要生成这个:

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
</ul>
<ul>
  <li>five</li>
  <li>six</li>
  <li>seven</li>
  <li>eight</li>
</ul>

以下是一些规则:

  • 如果没有物品,我不想要任何东西吐出来
  • 如果有16项或16项以下,则每<ul>
  • ID为4项
  • 如果有超过16个项目,我希望它能够均匀展开
  • 我必须按字母顺序重新排序商品。如果有17个项目,则第17个项目需要转到第一列,但所有内容都需要重新排序。

到目前为止我所拥有的:

function divide( $by, $array ) {
 14     $total = count( $array );
 15     $return = array();
 16     $index=0;
 17     $remainder = $total % $by !== 0;
 18     $perRow = $remainder ?
 19         $total / $by + 1:
 20         $total / $by
 21         ;
 22 
 23     for ( $j = 0; $j<$by; $j++ ) {
 24         //$return[] = array();
 25 
 26         if ( $index == 0 ) {
 27             $slice = array_slice( $array, 0, $perRow );
 28             $index = $perRow;
 29             $return[$j] = $slice;
 30         } else {
 31             $slice = array_slice( $array, $index, $perRow );
 32             $index = $index+$perRow;
 33             $return[$j] = $slice;
 34         }
 35     }
}

我输入一个数字,比如divide(4,$ arrRef),数字指示列的数量,但我需要重构以确定列数

4 个答案:

答案 0 :(得分:5)

我在视图模板中使用了这段代码..

<?php
$col = 3;
$projects = array_chunk($projects, ceil(count($projects) / $col));

foreach ($projects as $i => $project_chunk)
{
    echo "<ul class='pcol{$i+1}'>";
    foreach ($project_chunk as $project)
        {
        echo "<li>{$project->name}</li>";
    };
    echo "</ul>";
}; ?>

答案 1 :(得分:3)

你的要求非常奇怪/模糊,但我认为这就是你所要求的

function columnize( array $set, $maxCols = 4 )
{
  if ( count( $set ) <= 16 )
  {
    return array_chunk( $set, 4 );
  }

  return array_chunk( $set, ceil( count( $set ) / $maxCols ) );
}

答案 2 :(得分:3)

如果我理解正确,您希望将您的项目“智能地”分成四列,以便在并排放置时可以逻辑地阅读这些列表。如果是这种情况,这应该可以解决问题:

function columnize($items, $columns = 4, $min_per_column = 4) {

    if(empty($items)) return array();

    $result     = array();
    $count      = count($items);
    $min_count  = $min_per_column * $columns;

    if($count <= $min_count) {
        $columns = ceil($count / $min_per_column);
    } else {    
        $per_column = floor($count / $columns);
        $overflow   = count($items) % $columns;
    }

    for($column = 0; $column < $columns; $column++) {
        if($count <= $min_count) {
            $item_count = $min_per_column;
        } else {
            $item_count = $per_column;
            if($overflow > 0) {
                $item_count++;
                $overflow--;
            }
        }
        $result[$column] = array_slice($items, 0, $item_count);
        $items = array_slice($items, $item_count);
    }

    return $result;
}

你可以在这里测试一下:

  

http://www.ulmanen.fi/stuff/columnize.php

答案 3 :(得分:0)