订单结果为2列

时间:2012-04-05 09:01:31

标签: php css foreach

我有一个(php)数组,包含1,2,3,4,5或6个结果。我想在不同情况下将它们显示为以下内容:

1结果:

[result 1]

2结果:

[result 1]  [result 2]

3结果:

[result 1]  [result 3]
[result 2]

4结果:

[result 1]  [result 3]
[result 2]  [result 4]

5结果:

[result 1]  [result 4]
[result 2]  [result 5]
[result 3]

6结果:

[result 1]  [result 4]
[result 2]  [result 5]
[result 3]  [result 6]

如果我只能使用CSS(当然不能使用表格),那将是很好的,所以正确的顺序保留在源代码中,但显示如上所示。否则我想我需要一些奇怪的PHP循环来在我的屏幕上以正确的顺序获得这些结果。有人知道怎么做吗?提前谢谢!

3 个答案:

答案 0 :(得分:0)

它猜不可能只用css做一些事情。您必须将数组拆分为两个,并将前半部分显示到第一列,将后半部分显示到第二列。应该不是很难吗?

答案 1 :(得分:0)

这样的东西
$out = "<table><tbody>";
for ($i = 0; $i < count($array); $i++){
    $el = $array[$i];
    if(($i % 2) === 0){
        $out .= '<tr>';
    }
    $out .= "<td>$el</td>";
    //Handlethe case that this is the last iteration and 
    //the elements of the array are odd
    if((($i % 2) === 1) && (($i + 1) === count($array))){
        $out .= "<td></td></tr>";
    }elseif(($i % 2) === 1){
        $out .= "</tr>";
    }
}

$out .= "</tbody></table>";

答案 2 :(得分:0)

$array = array( 1, 2, 3, 4, 5, 6, 7 );

$number_of_columns = floatval(2.0); // float to make the below ceil work
$number_of_items = count( $array );
$items_per_column = ceil( $number_of_items / $number_of_columns );
$current_column = 0;

for ( $i = 0; $i < $number_of_items; $i++ ){

    if ( $i % items_per_column == 0 ){ 
        $current_column++;
    }

    echo $i, ' -> ', $current_column, '<br />';
}   
相关问题