带有分组项的PHP Foreach循环

Pau*_*aul 1 php arrays sorting foreach

我有一系列状态,我想要做的是用第一个字母对它们进行分类,然后显示这些组.我几乎正常工作,最后一个问题是:

到目前为止我有什么

我希望所有状态都在逗号分隔的单个框中,而不是每个状态都在它自己的灰色框中.这是我的代码:

<?
    $lastChar = '';
    sort($state_list, SORT_STRING | SORT_FLAG_CASE);

    foreach ($state_list as $state) {
        $char = $state[0];
        echo "<div class=\"stateTable\">";
        if ($char !== $lastChar) {
            echo "<div class=\"stateTopRow\">" . strtoupper($char) . "</div>";
                echo "<div class=\"clear\"></div>";
        $lastChar = $char;
        }
            echo "<div class=\"stateBody\">" . $state . "</div>";
                echo "<div class=\"clear\"></div>";
        echo "</div>";
    }
?>
Run Code Online (Sandbox Code Playgroud)

问题在于它为每个单独的状态循环整个stateBody div.我已经尝试过以某种方式在if语句中包含stateBody,但这完全打破了样式(并且理所当然).

有没有办法在if语句中包含stateBody,然后添加另一个foreach来循环通过相应的状态?谢谢!

Mic*_*ski 5

我建议采用略有不同的方法.由于您最终希望将它们全部分组,因此最好通过相应地组织阵列来开始.循环遍历它,并创建一个新数组,其子数组由第一个字母索引.在迭代原始数组时,在适当字符的索引处追加到新数组.然后,为您的输出循环更容易.

将数据格式化为最终需要的结构通常是一个好主意,允许您稍后简化输出逻辑.

// Start by sorting as you already did
sort($state_list, SORT_STRING | SORT_FLAG_CASE);

// Create a new array
$output_array = array();

// Loop over the one you have...
foreach ($state_list as $state) {
  $first = strtoupper($state[0]);
  // Create the sub-array if it doesn't exist
  if (!isset($output_array[$first])) {
    $ouput_array[$first] = array();
  }

  // Then append the state onto it
  $output_array[$first][] = $state;
}
Run Code Online (Sandbox Code Playgroud)

结果数组看起来像:

Array
(
    [A] => Array
        (
            [0] => Alabama
            [1] => Arkansas
            [2] => Alaska
        )

    [C] => Array
        (
            [0] => Connecticut
        )

)
Run Code Online (Sandbox Code Playgroud)

现在你只需要一个简单的循环implode()来产生你的输出:

// For clarity, I omitted your surrounding <div> markup
// this is just the first letter and the state lists...
foreach($output_array as $state_index => $states) {
  // The index is the first letter...
  echo "<div class='stateTopRow'>$state_index</div>";

  // And the sub-array can be joined with implode()
  echo "<div class='stateBody'>" . implode(', ', $states) . "</div>";
}
Run Code Online (Sandbox Code Playgroud)