如何根据对象值对数组列表进行排序

时间:2022-09-11 13:42:15

we need to list an array sorting by an object value.

我们需要列出一个按对象值排序的数组。

We have a list of films, sorted by alphabetical order, but we want to sort by genres.

我们有一个电影列表,按字母顺序排序,但我们想按类型排序。

here is the code listing in alphabetical order.

这是按字母顺序排列的代码。

<?php
    foreach ($films as $film_id => $film) {

    echo "<ul>";
    echo '<li id="film_thumb">';
    echo '<a href="watch.php?id=' . $film_id . '" alt="ID">';
    echo '<img class="thumb_res" src=" ' . $film["thumb"] . '" alt="' . $film["name"] . '">' ;
    echo '</a>';
    echo '</li>';
    echo "</ul>";
} ?>

the function listing in alphabetical order is in the array file

按字母顺序排列的函数列表位于数组文件中

sort($films, SORT_FLAG_CASE);

Here is the array

这是阵列

$films = array ();
    $films[1] = array(
        "name" => "21 Jump Street",
        "year" => "2012",
        "genre" => "Commedia",
        "path" => "media/01.mp4",
        "thumb"=> "media/thumb/01.png",
        );

now, we need to create a page that list these items ( film thumb ) in categories, so if i click on genre "Action", the page must to show only selected film genre, and not the others.

现在,我们需要创建一个页面,列出这些项目(电影拇指)的类别,所以如果我点击类型“动作”,页面必须只显示选定的电影类型,而不是其他。

Many thanks, Andrea

非常感谢,安德里亚

1 个解决方案

#1


1  

You can sort your array by genre with usort() :

您可以使用usort()按类型对数组进行排序:

usort($films, function($a, $b){
    return strcasecmp($a['genre'], $b['genre']);
});

If you want to get films from the selected genre, you can use array_filter() :

如果您想从所选类型中获取电影,可以使用array_filter():

$films = array_filter($films, function($film){
    return $film['genre'] == 'Commedia';
});

#1


1  

You can sort your array by genre with usort() :

您可以使用usort()按类型对数组进行排序:

usort($films, function($a, $b){
    return strcasecmp($a['genre'], $b['genre']);
});

If you want to get films from the selected genre, you can use array_filter() :

如果您想从所选类型中获取电影,可以使用array_filter():

$films = array_filter($films, function($film){
    return $film['genre'] == 'Commedia';
});