2017-04-03 79 views
0

我想對4個數組進行排序,但是我不知道如何去做。Laravel如何排序多維數組

$poster = []; 
    $character = []; 
    $title = []; 
    $date = []; 

    foreach($person->getMovieCredits()->getCast() as $movie) 
    { 
     array_push($poster, $movie->getPosterPath()); 
     array_push($character, $movie->getCharacter()); 
     array_push($title, $movie->getTitle()); 
     array_push($date, $movie->getReleaseDate()->format('Y')); 
    } 

    $personArray = [ 
     'date' => $date, 
     'title' => $title, 
     'character' => $character, 
     'poster' => $poster 
    ]; 

事情是,我想按日期對它們進行排序,但不會丟失與其他數組的數據完整性。

我該怎麼做?

+1

http://stackoverflow.com/questions/2910611/php-sort-a-multidimensional-array- by-element-containing-date –

+0

嘗試'ksort'閱讀更多[here](http://php.net/manual/en/function.ksort.php) –

+1

'array_multisort($ date,$ poster,$ character,$標題);' –

回答

0

試試這個

<?php 
$date = ['2014-04-03', '2013-04-03', '2015-04-03', '2017-04-03', '2013-09-03']; 
$title = ['title1', 'title2', 'title4', 'title5', 'title6']; 
$character = ['character2', 'character5', 'character1', 'character8', 'character0']; 
$poster = ['poster4', 'poster1', 'poster7', 'poster9', 'poster0']; 

$personArray = [ 
    'date' => $date, 
    'title' => $title, 
    'character' => $character, 
    'poster' => $poster 
]; 

/*echo "<pre>"; 
print_r($personArray);*/ 

$length_count = count($date); 

$new_array = array(); 
for($i=0; $i<$length_count ; $i++){ 
$new_array[$i] = array(); 
    foreach($personArray as $key => $value){ 
     $new_array[$i][$key] = $personArray[$key][$i]; 
    } 
} 

function date_compare($a, $b){ 
    $t1 = strtotime($a['date']); 
    $t2 = strtotime($b['date']); 
    return $t1 - $t2; 
}  
usort($new_array, 'date_compare'); 

//print_r($new_array); 
$sorted_array = array(); 
$sorted_array['date'] = array(); 
$sorted_array['title'] = array(); 
$sorted_array['character'] = array(); 
$sorted_array['poster'] = array(); 
foreach($new_array as $data){ 
    array_push($sorted_array['date'], $data['date']); 
    array_push($sorted_array['title'], $data['title']); 
    array_push($sorted_array['character'], $data['character']); 
    array_push($sorted_array['poster'], $data['poster']); 
} 
//print_r($sorted_array); 

?> 
0

謝謝你們的幫助,我沒做到這一點很簡單:

$movieArray = []; 
    foreach($person->getMovieCredits()->getCast() as $movie) 
    { 
     array_push($movieArray, ['date' => $movie->getReleaseDate()->format('Y'), 'poster' => $movie->getPosterPath(), 
      'character' => $movie->getCharacter(), 'title' => $movie->getTitle()]); 
    } 

    asort($movieArray);