2015-08-13 57 views
1

今天排序很有趣!嘆。我有一大堆雄辯的模型,它們需要通過一個參數在數組中組合在一起,然後在基於另一個參數的「塊」中排序。這可能是很難解釋:(通過2個參數對Laravel系列進行排序

$主口若懸河結果的收集,我不知道如何將它們寫在這裏,遍歷這個我可以訪問所有的模型功能/關係

$master = []; 

這些具有2個屬性需要成爲一個排序的基礎,例如性能低於

//Object 1 
$master->carry = 0; 
$master->section = 'red'; 

//Object 2 
$master->carry = 1; 
$master->section = 'blue'; 

//Object 3 
$master->carry = 0; 
$master->section = 'blue'; 

我希望讓每個$主 - >部分是一個「叢來排序的這些大量收集'在數組中,並在'叢''$ master-> carry = 0產品ar最後列出。

From the example above I'd expect Object1, Object3, Object2 

我試過主 - 幾個不同的$>的sort()和$主 - > sortBy()的東西,但每個新的排序拋出了舊排序:(

我有目前下面的代碼,這組了所有的顏色,但基於$主 - >如果不命令他們攜帶又

$order = array('red', 'blue', 'green'); 

    $master = $master->sort(function ($a, $b) use ($order) { 
     $pos_a = array_search($a->sectionheader, $order); 
     $pos_b = array_search($b->sectionheader, $order); 
     return $pos_a - $pos_b; 
    }); 

回答

2

我的理解,要排序您的收藏方式如下:

  • 排序的順序截面部內存儲在$順序陣列
  • 進位= 0移動元件與端

您必須通過將實現這樣的邏輯到功能$主人集合。該函數應該採取2個參數(集合的2個元件),對它們進行比較,並返回:

  • 如果元素相等
  • 如果第一元件比第二元件更大
  • -1如果第一個元素是比第二元素

在你的情況要小以下的回調應該工作:

$master = $master->sort(function ($a, $b) use ($order) { 
    // get order of first element's section 
    $pos_a = array_search($a->section, $order); 
    // get order of second element's section 
    $pos_b = array_search($b->section, $order) 
    // if sections are different the value of carry doesn't matter 
    // as element's sections are enough to determine which of them is larger 
    if ($pos_a != $pos_b) { 
    return $pos_a - $pos_b; 
    } 

    // carry values are equal, so consider elements equal 
    if ($a->carry == $b->carry) { 
    return 0; 
    } 

    if (!$a->carry) { 
    // if $a->carry is equal to 0 it should be put at the end, so after $b 
    return 1; 
    } 

    if (!$b->carry) { 
    // if $b->carry is equal to 0 it should be put at the end, so after $a 
    return -1; 
    } 

    // otherwise elements can be considered equal 
    return 0; 
}); 
+0

這真的很接近我想,非常感謝你的配偶(這是今天你第二次來到一個驚人的例子,所以啤酒就在我身上)。然而,這似乎完全拋棄了叢集所在的原始順序(id ASC),是否有辦法只將進位項目排序到每個部分的底部,而不交換每個「叢塊」的順序 - 我只是在運送物品之外實現的是收集的結束,其他一切都按照正確的順序進行。 –

+0

沒關係,我添加了$ a-> id和$ b-> id的回報,它的工作完美。你的時間和精力非常感謝。謝了哥們!!! –

+0

你是在哪裏添加的?我將在第一個if()語句之後更新答案 –

相關問題