我有一个非常不寻常的排序问题。我必须按照我现在在数据库中预先定义的位置来安排项目:
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
,因此根据计划,所有排序值不等于零的项目应放在其他项目之前。
这是当前的代码:
<?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。
答案 0 :(得分:0)
请尝试以下
$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 } ?>