使用键和值为每行创建有限列表

时间:2015-08-18 18:37:33

标签: php arrays foreach

所以我需要这样的东西,因为我已经让它工作了,但我需要用键和值来表达它。所以我有一个具有状态和值的数组。所以我希望能够创建这个结果,我可以回显状态和值。

这不是整个数组,而是示例:

$states = array('AL'=>"Alabama",
            'AK'=>"Alaska",
            'AZ'=>"Arizona",
            'AR'=>"Arkansas",
            'CA'=>"California",
            'CO'=>"Colorado",
            'CT'=>"Connecticut",
            'DE'=>"Delaware",
            'FL'=>"Florida",
            'GA'=>"Georgia",

$states = statesList();
            $lists  = array_chunk($states, 10);
            $number = 1;
            foreach ($lists as $items) {
            echo '<ul class="row', $number++, '">';
            foreach ($items as $item) {
            echo '<li>', $item, '</li>';
            }
            echo '</ul>';
            }

1 个答案:

答案 0 :(得分:0)

只需一个简单的foreach即可。

$count = 0;
foreach ($states as $key => $value)
{
    echo $key." is ".$value. "<br>";
    $count++;
    if ($count == 5)  // print only 5 elements
        break;
}

输出:

AL is Alabama
AK is Alaska
AZ is Arizona
AR is Arkansas
CA is California