将动态数量的项目划分为列 [英] Dividing up a dynamic number of items into columns

查看:62
本文介绍了将动态数量的项目划分为列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有动态的项目数量,需要将其分为几列.假设我得到了这个:

I have a dynamic number of items in which I'll need to divide into columns. Let's say I'm given this:

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个项目需要转到第一列,但所有内容都需要重新排序.
  • if there are no items, I don't want anything to be spat out
  • if there are 16 or under 16 items, id like 4 items per <ul>
  • if there are more than 16 items, i'd like it to be spread out evenly
  • i'll have to alphabetically reorder items. if there are 17 items, the 17th item will need to go to the first column but everything needs to be reordered.

到目前为止我所拥有的:

What I have so far:

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),该数字决定了列数,但是我需要重构以便确定列数

I feed a number, like divide( 4, $arrRef ), the number dictates the # of columns, but I need to refactor so it determines the number of columns

推荐答案

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

I used this code inside my view template..

<?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>";
}; ?>

这篇关于将动态数量的项目划分为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆