如何在php中按字母顺序排列值

时间:2018-03-21 18:13:56

标签: php

我正在研究工作门户项目,并希望按照字母顺序排列字母表,我希望以A开头的公司位于A列标题下,以B开头的公司位于B标题下。 ..” 或者,如果我没有B值的公司,则跳过B。

<span>a</span>
<?php         
    $sql = "select * from companies";
    $result = mysqli_query($con, $sql);
    while($data = mysqli_fetch_array($result)) {
        $company = $data['company_name'];
?>
 <div class="list-col"> <a href="#"><?php echo $company; ?>(0)</a>  </div>
<?php
    }
?>
 </div>
 </li>
<!-- Sample of how column in HTML -->
<li class="loop-entry">
  <div class="col"> 
    <span>C</span>
    <div class="list-col"> 
       <a href="#">Company Name (0)</a> 
       <a href="#">Company Name (1)</a> 
       <a href="#">Company Name (2)</a> 
       <a href="#">Company Name (3)</a> 
       <a href="#">Company Name (4)</a> 
   </div>
 </div>
</li>              

我想根据这张图片安排

enter image description here

1 个答案:

答案 0 :(得分:0)

好的,这是。我使用函数来捕获你想要的东西。稍后我将详细介绍您需要了解的内容。

我在PHP Sandbo x上完成了一个示例,其中包含一个值数组,用于显示在HTML中以文本形式输出的代码

<?php         
    $sql = "select * from companies ORDER BY company_name";
    $result = mysqli_query($con, $sql);
    $letter = '';
    $count = 0;
    while($data = mysqli_fetch_array($result)) {
        $company = $data['company_name'];
        createCompanyList($company, $letter,$count);
    }
/**
creates Company Listing
*/

function creatCompanyList($company, &$letter, &$count){

    if($letter !== $company[0]) {
          if($count >0) { 
              endCompanyList();
              $count = 0;
          }
          $letter = $company[0];
          startCompanyList($letter, $count);
     }

    //only adds the company if the letter and company matches 
    //and permits only the first 5 companies 
    if($letter == $company[0] && $count <= 4) addCompanyList($company);

    if($count==4) endCompanyList();
    $count++;
}

//creates opening divs for a Company List based upon letter
function startCompanyList($letter, &$count){
  ?>
  <li class="loop-entry">
  <div class="col"> <span><?=$letter?></span>
  <div class="list-col">
  <?php
}

//closes divs for the Company List
function endCompanyList(){   
  ?>
  </div>
  </div>
  </li>         
  <?php
}

//inserts company into to a column
function addCompanyList($company){
  ?>
  <a href="#"><?=$company?></a>
  <?php
}
?>