繁体   English   中英

Laravel 如何按特定值和 id 对集合进行排序

[英]Laravel how to sort collection by specific value and id

如何按特定名称和 ID 对 collections 进行排序。 我需要对记录进行排序,其中名称 = X 应该是顺序中的第一个,并且 rest 应该按 id 排序。

产品 model

|----|------|
| id | Name |
|----|------|
|  1 | a    |
|  2 | x    |
|  3 | b    |
|  4 | c    |
|  5 | x    |
|  6 | z    |
|----|------|

我尝试了这段代码,但没有工作。

Product::orderBy('id', 'asc')->get()

您可以使用 collections 及其方法...这里我使用数组...

试试这个...

$product = Product::orderBy('id', 'asc')->get();
$results =array_map("moveToFirst",$product);

function moveToFirst($product){
  $otherIndex = array_search('x',$product);
  if($otherIndex !== false){
      $v = $product[$otherIndex];
      unset($product[$otherIndex]);
      array_unshift($product , $v);
   }
  
  return $product;
}



|---------------------|------------------|
|          id         |        Name      |
|---------------------|------------------|
|          5          |         x        |
|---------------------|------------------|
|          2          |         x        |
|---------------------|------------------|
|          1          |         a        |
|---------------------|------------------|
|          3          |         b        |
|---------------------|------------------|
|          4          |         c        |
|---------------------|------------------|
|          6          |         z        |
|---------------------|------------------|

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM