0

创建一个大数组,然后排序,然后我应该得到例如排序数组的前 n 个元素。

创建数组:

foreach ($array_RESPONSEdata as $key => $row) {
 $new_created_time[$key] = $row['DATE_PIC'];
 $new_thumbnail[$key] = $row['LINK_PIC'];
 $new_tags_name [$key] = $row['TAG_PIC'];
}

在 get 数组的输出中,如下所示:

Array (
[0] => Array ( [DATE_PIC] => 1376566005 [LINK_PIC] => http://distilleryimage3.s3.amazonaws.com/90ebfcc2059d11e381c522000a9e035f_5.jpg [TAG_PIC] => test )
[1] => Array ( [DATE_PIC] => 1376222415 [LINK_PIC] => http://distilleryimage9.s3.amazonaws.com/957a78a4027d11e3a72522000a1fb586_5.jpg [TAG_PIC] => test )
[2] => Array ( [DATE_PIC] => 1374685904 [LINK_PIC] => http://distilleryimage2.s3.amazonaws.com/1dbe356ef48411e2931722000a1fc67c_5.jpg [TAG_PIC] => test )
[3] => Array ( [DATE_PIC] => 1373909177 [LINK_PIC] => http://distilleryimage0.s3.amazonaws.com/0fd9b22adce711e2a7ab22000a1f97eb_5.jpg [TAG_PIC] => test )
[4] => Array ( [DATE_PIC] => 1372089573 [LINK_PIC] => http://distilleryimage0.s3.amazonaws.com/0fd9b22adce711e2a7ab22000a1f97eb_5.jpg [TAG_PIC] => test )
[5] => Array ( [DATE_PIC] => 1371468982 [LINK_PIC] => http://distilleryimage0.s3.amazonaws.com/0fd9b22adce711e2a7ab22000a1f97eb_5.jpg [TAG_PIC] => test )
)

接下来,按 DATE_PIC 键对数组进行排序:

array_multisort($new_created_time, SORT_DESC, $array_RESPONSEdata);

得到一个反向排序的数组。


问题:现在如何排序后,输出前三行?

4

1 回答 1

0

您实际上不需要分开数组,如果它适合您的应用程序,这将节省一些内存:

<?php

    // Will sort using 'DATE_PIC' as index.
    array_multisort( $array_RESPONSEdata, SORT_ASC );

    // We'll define a buffer, so PHP doesn't need to echo every time (list-style).
    $buffer = array();

    /**
     * You mentioned 'get the first n elements', to specify how many
     * rows you want to get, you can specify the max count in a for loop
     * array_multisort reassigns numeric index keys in order after sorting.
     *
     * e.g. If we want 5 records to count:
     * $max = 5;
     *
     * If you want all that is returned you can do this:
     * $max = count( $array_RESPONSEdata );
     */
    $max = 5;

    for( $n = 0; $n < $max; $n++ )
    {
        $buffer[] = '<ul>';
        $buffer[] = '<li>' . $array_RESPONSEdata[$n]['TAG_PIC'] . '</li>';
        $buffer[] = '<li>' . $array_RESPONSEdata[$n]['DATE_PIC'] . '</li>';
        $buffer[] = '<li><img src="' . $array_RESPONSEdata[$n]['LINK_PIC'] . '" alt="' . $array_RESPONSEdata[$n]['TAG_PIC'] . '"/>';
        $buffer[] = '</ul>';
    }

    // And now the output magic (Not really):
    echo implode( "\r\n", $buffer );
?>

当然,根据需要构建您的 HTML,这只是示例。顺便说一句,作为参考,我将"\r\n"缓冲区拼接在一起,因为源代码打印在不同的行上,从而可以轻松查看源代码中发生的 html/css 调整。

于 2013-10-04T18:14:00.313 回答