PHP + MySQL - 获取行并均分

时间:2015-08-10 18:36:27

标签: php html mysql css

我想安排两侧的行。例如,

这是MySQL表格中的行

---------------------
|  1  | Apple       |
---------------------
|  2  | Banana      |
---------------------
|  3  | Cinnamon    |
---------------------
|  4  | Donkey      |
---------------------

我想把它取到:

<div class="col-md-6" >
  <ul>
    <li>Apple</li>
    <li>Banana</li>
  </ul>
</dil>
<div class="col-md-6" >
  <ul>
    <li>Cinnamon/li>
    <li>Donkey</li>
  </ul>
</dil>

我需要将行等分为两个html表列。有人可以帮忙吗?谢谢!

2 个答案:

答案 0 :(得分:1)

这个怎么样

$elements = <get elements from mysql server>;
$elementCount = count($elements);

echo "<div class=\"col-md-6\" >\n<ul>"

for ($i = 0; $i < $elementCount/2; $i++) { // start at the beginning, go to the halfway point
  echo '<li>' . $elements[$i] . '</li>';
}

echo '</div>'
echo "<div class=\"col-md-6\" >\n<ul>"

for ($i = $elementCount/2; $i < $elementCount; $i++) { // start at halfway point, go to the end
  echo '<li>' . $elements[$i] . '</li>';
}

echo '</div>'

通过获取列表中的元素数量并将我的两个分开,然后将其用作停止一个列表并启动另一个列表的点,在不同时间将列表分成两个单独的一半。

答案 1 :(得分:-1)

if $rows - 它是php代码中的行数组,你可以通过这种方式获得所需的数组:

$first_row = array();
$second_row = array();
foreach($rows as $num=>$row){
if($num<=count($rows)/2)$first_row[] = $row;
else{
$second_row[]=$row
}
}

承认只有当你有$行总数作为对时它才能正常工作。另一种方法是让数组$first_row$second_row中的元素数量略有不同

代码将是下一个:

//$rows = ... (get your rows with sql query) 
<?php
 $first_row = array();
    $second_row = array();
    foreach($rows as $num=>$row){
    if($num<=count($rows)/2)$first_row[] = $row;
    else{
    $second_row[]=$row
    }
    }
?>

<div class="col-md-6" >
  <ul>
    <? foreach($first_row as $f_row){ ?>
    <li><?php=$f_row ?></li>
    <?php } ?>
  </ul>
</div>
<div class="col-md-6" >
  <ul>
    <? foreach($second_row as $s_row){ ?>
    <li><?php=$s_row ?></li>
    <?php}?>
  </ul>
</div>
相关问题