使用两个不同的值排序嵌套的php数组

时间:2014-09-25 16:20:24

标签: php arrays sorting

我正在尝试先按[artist] [0] [name]排序数组,然后按[datetime]排序,这样我最终会得到类似

的内容
9/25 - Artist1
9/26 - Artist1
9/27 - Artist1
9/25 - Artist2
9/26 - Artist2
9/27 - Artist2
...

这是我从Feed中获取数据的方式:

Array
(
[0] => Array
    (
        [ticket_url] => ...
        [on_sale_datetime] => ...
        [ticket_status] => ...
        [url] => ...
        [venue] => Array
            (
                [longitude] => ...
                [region] => ...
                [city] => ...
                [url] => ...
                [country] => ...
                [id] => ...
                [latitude] => ...
                [name] => ...
            )

        [artists] => Array
            (
                [0] => Array
                    (
                        [mbid] => ...
                        [url] => ...
                        [name] => ...
                    )

            )

        [datetime] => ...
        [id] => ...
    )
)

我可以按[名称]排序很好,但无法弄清楚如何让[datetime]与每个[name]一起按顺序排列。这是我到目前为止所做的:

    $object = $x->eventSearch($artists, $location, null, "$today,$next_week", 1, 100);

    $array = objectToArray($object);

    usort($array, function($a, $b) {
        return strcmp($a['artists'][0]['name'], $b['artists'][0]['name']);
    });

    foreach ($array as $key => $val)
    {

        $main_artist = $val[artists][0][name];

        $dateofevent = date("m/d", strtotime($val[datetime]));
        $venue_city = $val[venue][city];
        $venue_region = $val[venue][region];
        $venue_name = $val[venue][name];
        ?>
        <tr>
            <td><?php echo $dateofevent; ?></td>
            <td><?php echo $main_artist; ?></td>
            <td><?php echo $venue_city . ", " . $venue_region; ?></td>
            <td><?php echo $venue_name; ?></td>
        </tr>
    <?php } ?>

非常感谢任何见解。

1 个答案:

答案 0 :(得分:0)

执行以下操作,按艺术家姓名排序,然后按日期/时间排序。

usort($array, function($a, $b) {
    $s = strcmp($a['artists'][0]['name'], $b['artists'][0]['name']);
    if($s != 0 ) { return $s; }
    datetime_comparison_here(); // your example data is helpfully '...'
});