2015-07-01 2 views
-2

Мне нужно отсортировать мой массив json в хронологическом порядке по его созданному значению времени.Laravel sort array by created_at

[{ 
    "id": 1, 
    "message": "hello", 
    "company_id": 7, 
    "investor_id": 35, 
    "match_id": 2, 
    "created_at": "2015-07-01 12:56:34", 
    "updated_at": "2015-07-01 12:56:34" 
    }, { 
    "id": 2, 
    "message": "helloWorld", 
    "company_id": 7, 
    "investor_id": 35, 
    "match_id": 2, 
    "created_at": "2015-07-01 12:56:53", 
    "updated_at": "2015-07-01 12:56:53" 
    }, { 
    "id": 3, 
    "message": "sup", 
    "company_id": 7, 
    "investor_id": 35, 
    "match_id": 2, 
    "created_at": "2015-07-01 13:12:53", 
    "updated_at": "2015-07-01 13:12:53" 
    }, { 
    "id": 4, 
    "message": "sup", 
    "company_id": 7, 
    "investor_id": 35, 
    "match_id": 2, 
    "created_at": "2015-07-01 13:13:04", 
    "updated_at": "2015-07-01 13:13:04" 
    }, { 
    "id": 5, 
    "message": "sup", 
    "company_id": 7, 
    "investor_id": 35, 
    "match_id": 2, 
    "created_at": "2015-07-01 15:06:39", 
    "updated_at": "2015-07-01 15:06:39" 
    }, { 
    "id": 1, 
    "message": "yo yo ", 
    "investor_id": 35, 
    "company_id": 7, 
    "match_id": 2, 
    "created_at": "2015-07-01 22:09:36", 
    "updated_at": "-0001-11-30 00:00:00" 
    }, { 
    "id": 2, 
    "message": "sup nigga", 
    "investor_id": 35, 
    "company_id": 7, 
    "match_id": 2, 
    "created_at": "2015-07-01 14:00:00", 
    "updated_at": "-0001-11-30 00:00:00" 
    }] 

Может ли кто-нибудь научить меня, как я пробовал много решений в stackoverflow. Многие из них говорят, что массив не может использоваться с «sortBy».

Это часть моего кода:

$companyMessage = Company_Message::where('match_id','=',$match_id); 
    $investorMessage = Investor_Message::where('match_id','=',$match_id); 
    $message = array(); 
    if($companyMessage->count()>0 || $investorMessage->count() > 0){ 
     if($lastActivityDate == null){ 
      //load all messages before 
      if($companyMessage !=null){ 
       foreach ($companyMessage->get() as $cm) { 
        array_push($message,$cm); 
       } 
      } 

      if($investorMessage !=null){ 
       foreach($investorMessage->get() as $im){ 
        array_push($message,$im); 
       } 
      } 

      return $message ; 

     } 
+0

как вы запрашиваете это? Я имею в виду, как вы получили эти выходные красноречивые отношения? как ? –

ответ

1

Я думаю, что вы можете сделать это, используя использовать Laravel базу данных collection api вместо array и добавить элемент в коллекции и использовать sortBy метод по сбору,

$col = new \Illuminate\Database\Eloquent\Collection(); 

if ($companyMessage != null) { 
    foreach($companyMessage - > get() as $cm) { 
    $col->add($cm); 
    } 
} 
if ($investorMessage != null) { 
    foreach($investorMessage - > get() as $im) { 
    $col->add($im);  
    } 
} 

$col = $col->sortBy('created_at'); 

//return the json 
return Response::json($jsonArr->toArray()); 

--- OR ----

Попробуйте это, но я не сделал - сказал он. Если это сработает, тогда это будет лучший способ сделать это.

$companyMessage = Company_Message::where('match_id','=',$match_id); 
$investorMessage = Investor_Message::where('match_id','=',$match_id); 

//$companyMessage & $investorMessage both are laravel database collection, 
// so you can use merge method on collection to merge these two collections. 

$allResults = $companyMessage->merge($investorMessage); 

//use laravel collection sort method to sort the collection by created_at 
$allResults = $allResults->sortBy('created_at'); 

//return the json 
return Response::json($allResults->toArray());  
+0

привет, я пробовал оба. он не работал. он по-прежнему отображается так же, как то, что я опубликовал –

+0

проверить, что вы выводили отсортированную коллекцию, а не объединенную коллекцию? –

+0

вот что я получаю от этого. ' "4": { "идентификатор": 5, "сообщение": "SUP", "company_id": 7, "investor_id": 35, "match_id": 2, "created_at":" 2015-07-01 15:06:39 ", " updated_at ":" 2015-07-01 15:06:39 " }, " 5 ": { " id ": 1, " message ": "Yo Yo", "investor_id": 35, "company_id": 7, "match_id": 2, "created_at": "2015-07-01 22:09:36", "updated_at": " -0001-11-30 00:00:00 " }, " 6 ": { " id ": 2, "сообщение": "SUP SUP", "investor_id": 35, "company_id": 7, "match_id": 2, "created_at": "2015-07-01 14:00:00", "updated_at": "-0001-11-30 00:00:00" } ' –

1
if($companyMessage !=null){ 
    foreach ($companyMessage->get() as $cm) { 
     array_push($message,$cm);      
    } 
} 

if($investorMessage !=null){ 
    foreach($investorMessage->get() as $im){ 
     array_push($message,$im); 
    } 
} 

$message = array_values(array_sort($message, function ($value) { 
    return $value['created_at']; 
})); 

Эй человек, я нашел лучшее решение, чтобы сортировать мой массив. Ответ можно найти на Laravel документы

http://laravel.com/docs/5.1/helpers#method-array-sort

+0

проверить время выполнения обоих случаев –