我遇到了一个非常不寻常的排序问题。我必须按照预定义的位置排列项目,就像我现在在数据库中的位置一样:
sid - auto increment
name - just something to distinguish varchar 100
sorting - this is where we define the exact position of the item
如果我们给任何产品sorting = 2
,它无论如何都会排在第二位。但它应该由排序定义。
我无法使用 order by sorting desc
来排列项目,因为大多数项目都没有分配任何位置。由于某些已分配值的条目具有 sorting = 0
,因此根据计划,所有排序值不等于 0 的项目都应放在其他项目之前。
这是当前代码:
<?php
$conn=mysqli_connect("localhost","root","","work");
$getthedetails=mysqli_query($conn,"select sid,sorting,name from sorting order by sorting asc");
while($thelistis=mysqli_fetch_array($getthedetails)){ ?>
<div style="width:100px;font-weight:bold;color:#000;font-size:19px;font- family:arial;height:100px;padding:49px;background:silver;float:left;margin:10px;">
<?=$thelistis['sorting']?>
</div>
<?php } ?>
理想情况下,我希望排序类似于 1,0,0,4,5,0,0,8。
我想要的是类似 this 的东西.
最佳答案
在下面试试这个
$getthedetails=mysqli_query($conn,"select id,sorting,name from tbl_sorting order by sorting asc");
$arrayList = array();
while($thelistis=mysqli_fetch_array($getthedetails)){
$arrayList[] = $thelistis;
}
foreach($arrayList as $key=>$list){
if($list['sorting'] != 0){
//Keep current element of array
$temp = $arrayList[$key];
//Make current element same as with the one to swap
$arrayList[$key] = $arrayList[$list['sorting']-1];
//Swap the kept one to its place
$arrayList[$list['sorting']-1] = $temp;
}
}
foreach($arrayList as $key=>$list){?>
<div style="width:100px;font-weight:bold;color:#000;font-size:19px;font- family:arial;height:100px;padding:49px;background:silver;float:left;margin:10px;">
<?php echo $list['sorting']?>
</div>
<?php } ?>
关于php - 数据的异常排序 - 按固定数据 id 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33168234/