如何将数组值平均分配给三个单独的div

时间:2015-08-17 18:37:38

标签: php arrays

我有一个包含汽车功能的数组。我使用自举网格系统,并想在三个col-md-4 div中列出这些数组元素,所以它们看起来像这样:

<div class="col-md-4">
    Air Conditioning<br />
    Power Windows<br />
    Power Locks<br />
    Power Steering<br />
    Tilt Wheel<br />
    AM/FM CD/MP3
</div>
<div class="col-md-4">
    Satellite<br />
    Immobilizer<br />
    Keyless Entry<br />
    Alarm<br />
    Daytime Running Lights<br />
    Dual Front Airbags
</div>
<div class="col-md-4">
    Side Airbags<br />
    Head Airbags<br />
    Rear Head Airbags<br />
    Active Seatbelts<br />
    All Wheel ABS<br />
    Power Sun/Moon Roof
</div>

从这样的列表:

<?php
$feature_list = "Air Conditioning; Power Windows; Power Locks; Power Steering; Tilt Wheel; AM/FM CD/MP3; Satellite; AM/FM CD/DVD; Immobilizer; Keyless Entry; Alarm; Daytime Running Lights; Dual Front Airbags; Side Airbags; Head Airbags; Rear Head Airbags; Active Seatbelts; All Wheel ABS; Power Sun/Moon Roof;"

$feature_list = explode(';', $feature_list);
?>

如何以一种将这些数组值均匀分配给div的方式循环遍历数组?

2 个答案:

答案 0 :(得分:2)

您只需使用array_chunk即可。

// split array into three arrays. The last may have fewer items than the rest.
$feature_list_columns = array_chunk($feature_list, (int)(count($feature_list) / 3));

你没有说出你是如何输出它们的,但这可行

$output = '';
foreach ($feature_list_columns as $column){
    $output .= '<div class="col-md-4">' . implode("<br />", $column) . '</div><!--/.col-md-4-->';
}
echo $output;

答案 1 :(得分:0)

试试这个:

    <?php 
$feature_list = "Air Conditioning; Power Windows; Power Locks; Power Steering; Tilt Wheel; AM/FM CD/MP3; Satellite; AM/FM CD/DVD; Immobilizer; Keyless Entry; Alarm; Daytime Running Lights; Dual Front Airbags; Side Airbags; Head Airbags; Rear Head Airbags; Active Seatbelts; All Wheel ABS; Power Sun/Moon Roof;";
$feature_list = explode(';', $feature_list);
echo"<div class=\"col-md-4\"> ";
for ($i = 0; $i < count($feature_list); $i++) {
    echo $feature_list[$i]."<br/>";
    if (($i+1)%6==0) {
        echo "</div><div class=\"col-md-4\"> ";
    }
}
echo "</div>";
?>