Laravel如何对多维数组进行排序

时间:2017-04-03 04:12:55

标签: php arrays laravel sorting multidimensional-array

我想对包含在1个数组中的4个数组进行排序,但我不知道如何做到这一点。

    $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
    ];

问题是我希望按日期对它们进行排序,但不会因其他数组而丢失数据完整性。

我该怎么做?

3 个答案:

答案 0 :(得分: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);

?>

答案 1 :(得分:0)

您还可以使用Laravel助手array_sort()array_sort_recursive()。在Closure中,你检查父数组also is an array中的元素是否也对内部数组进行排序。

https://laravel.com/docs/5.4/helpers

答案 2 :(得分: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);