du6333137 2014-01-22 02:03
浏览 171
已采纳

带有分组项的PHP Foreach循环

I have an array of States, and what I'm trying to do is categorize them by first letter and then display the groups. I have it almost working properly, there's one final problem:

what I have so far

Instead of each state being in it's own gray box, I want all of the states in a single box separated by comma. This is my code:

<?
    $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>";
    }
?>

The issue is that it's looping the entire stateBody div for each individual state. I've tried somehow including stateBody within the if statement, but that breaks the styling entirely (and rightfully so).

Is there some way to include stateBody within the if statement and then add another foreach to loop through the corresponding states? Thank you!

  • 写回答

5条回答 默认 最新

  • du12197 2014-01-22 02:13
    关注

    I would recommend a slightly different approach. Since you ultimately want them all grouped, it would be better to start out by organizing your array accordingly. Loop over it, and create a new array with sub-arrays indexed by the first letter. As you iterate the original array, append to the new one at the index of the appropriate character. It then becomes much easier to loop over it for your output.

    It's often a good idea to format your data into the structure you ultimately need from the get-go, allowing you to simplify your output logic later.

    // 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;
    }
    

    The resultant array looks like:

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

    Now you just need a simple loop and an implode() to produce your output:

    // 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>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类