php - 数据的异常排序 - 按固定数据 id 排序

标签 php mysql sorting sql-order-by

我遇到了一个非常不寻常的排序问题。我必须按照预定义的位置排列项目,就像我现在在数据库中的位置一样:

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 } ?>

enter image description here

关于php - 数据的异常排序 - 按固定数据 id 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33168234/

相关文章:

php - 在 PHP 中,什么时候应该使用静态方法与抽象类?

php - 如何改进以下 mysql 选择?

java - 如何使用数据库中的数据填充 ListView

c - 快速排序:为什么输出错误

php - 提交时将输入值保存到文本文件吗?

php - 按自定义顺序对帖子进行排序

r - 使用 DT 包的数据表中的排序因素

ruby-on-rails - Rails 3 复杂排序

MySQL GROUP BY - 每组显示 X 个结果

mysql - 为什么在 "JOIN (SELECT)"语句中使用别名会导致错误?