如何在php中按字母顺序排列值
问题描述:
I am working on job portal project, and want to arrange values alphabetically according to their starting alphabet section, I want companies starting with A to be under the A column header, and companies starting with B to be under the B header..." or if i have no companies with the value of B then B be skipped.
<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>
i wants to arrange according to this image
答
Okay here it is. I used functions to capture what you wanted. I will detail more later to explain things that you need to understand.
I completed an example on PHP Sandbox with an array of values to display the code as outputted in text in 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
}
?>