2016-03-23 15 views
4

Ich habe diese Sammlung Ergebnis:Laravel Art Sammlung von Datum

$result = [{ 
    "date": "2016-03-21", 
    "total_earned": "101214.00" 
}, 
{ 
    "date": "2016-03-22", 
    "total_earned": "94334.00" 
}, 
{ 
    "date": "2016-03-23", 
    "total_earned": "96422.00" 
}, 
{ 
    "date": "2016-02-23", 
    "total_earned": 0 
}, 
{ 
    "date": "2016-02-24", 
    "total_earned": 0 
}, 
{ 
    "date": "2016-02-25", 
    "total_earned": 0 
}] 

Ich mag das Ergebnis nach Datum sortieren:

$sorted = $transaction->sortBy('date')->values()->all(); 

Aber ich habe nicht das erwartete Ergebnis:

[{ 
    "date": "2016-02-23", 
    "total_earned": 0 

}, 
{ 
    "date": "2016-02-24", 
    "total_earned": 0 
}, 
{ 
    "date": "2016-02-25", 
    "total_earned": 0 
}, 
{ 
    "date": "2016-03-22", 
    "total_earned": "94334.00" 
}, 
{ 
    "date": "2016-03-21", 
    "total_earned": "101214.00" 
}, 
{ 
    "date": "2016-03-23", 
    "total_earned": "96422.00" 
}] 

Wie Sie sehen können alle mit Monat 2 ist richtig sortieren. Jedoch im Monat 3 beginnt es versaut. (Das tatsächliche Ergebnis ist länger als das und es verpatzt Start um Monat 3)

Jede Lösung, um es richtig zu sortieren?

Danke.

+0

, was die Art der Spalte 'date' haben? –

+0

@ChetanAmeta Hallo. Datumstyp ist String – ssuhat

+1

Funktioniert 'orderBy (' date ',' ASC ')? –

Antwort

4

versuchen, etwas like this:

$sorted = $transaction->sortBy(function($col) 
{ 
    return $col; 
})->values()->all(); 
+0

Es funktioniert !. aber ich muss '-> date 'entfernen, damit es funktioniert. Wenn nicht, wird es mir zurückgeben 'versuchen, Eigentum von Nicht-Objekt zu bekommen ' – ssuhat

+0

Danke für die Antwort, ich habe den Code behoben. –

+1

danke, du hast mich gerettet! –

0

können Sie versuchen,

$transaction->groupBy('date'); 

Und seien Sie sicher, dass $ Transaktion eine Sammlung ist;

+0

Hallo, Wenn ich es gruppiere, wird es getrenntes Array. und es ist nicht sortiert – ssuhat

0

hatte ich das gleiche Problem. Ich habe dieses Makro erstellt.

Collection::macro('sortByDate', function ($column = 'created_at', $order = SORT_DESC) { 
    /* @var $this Collection */ 
    return $this->sortBy(function ($comment) use ($column) { 
     return strtotime($comment->$column); 
    }, SORT_REGULAR, $order == SORT_DESC); 
}); 

ich es wie folgt verwendet werden:

$comments = $job->comments->merge($job->customer->comments)->sortByDate('created_at', true);