Mysql - 将数据拆分为div

时间:2011-07-25 18:17:50

标签: php mysql html split

我有一个名为“Names”的表,它包含大约400个输入。 我希望每50个名字都在一个div中。

<div id="1">name1, name2, ... name50</div>
<div id="2">name51,name52, ... name100</div> and so on ...

任何帮助?

2 个答案:

答案 0 :(得分:0)

这样的事情至少应该是一个好的开始:

for ($n = 0; $n< 140; $n++) {
    $names[] = 'name'.$n;
}

$n = 0;
$div = 0;
foreach ($names as $name) {
    if ($n%50 == 0) {
        $div++;
        echo '<div id="'.$div.'">';
    }
    echo $name . ', ';
    if ($n%50 == 49) {
        echo '</div>';
    }
    $n++;
}
echo '</div>';

答案 1 :(得分:0)

使用以下脚本很容易实现(希望我跳过语法错误):

<?php
    //Get the names
    $names_res = mysql_query("SELECT names FROM Names");

    //Set a counter
    $counter = 0;

    //Loop over the names
    while( $name_arr = mysql_fetch_assoc($names_res) )

        //Let's see now...
        if( ($counter % 50 == 0) || $counter == 0  ) 
            echo '<div id="', ( ($counter == 0)? 1 : ($counter/50)+1 ) , '">';    

        //Output the name
        echo $name_array['name'] , ( ($counter % 49 === 0 )? '' : ', ' );

        //Close the div if neccesary
        if( ($counter % 49 == 0) || $counter == 0 ) echo '</div>';

        //Yes, we do want to increment it
        $i++;
    }
?>
祝你好运!