【问题标题】:Unusual sorting of data - order by fixed data id数据的异常排序 - 按固定数据 id 排序
【发布时间】:2015-10-16 10:28:44
【问题描述】:

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

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。

【问题讨论】:

  • 试试ORDER BY -sorting DESC
  • @TerisL 它将无法正常工作,因为我一直在使用它。它不起作用,因为排序对于未排序的项目可以有 value=0
  • 列和表都命名为“排序”?
  • 是的......但这不是任何问题,我将更改表名,这只是为了测试目的
  • 不知道是否可以通过查询,我会处理一些事情并用PHP告诉你

标签: php mysql sorting sql-order-by


【解决方案1】:

在下面试试这个

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

【讨论】:

  • 您好,答案是正确的,但是当我通过排序 desc 使用 order 时,它失败了。我想要的是用预定义的值排列项目,如果该值为空白,那么最后输入的应该排在第一位..
猜你喜欢
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多