在 PHP 中对多维数组进行排序? [英] Sorting a multidimensional array in PHP?
问题描述
我有这种数组
array(5) {[0]=>数组(5){[0]=>字符串(7)jannala"[1]=>字符串(10)2009-11-16"[2]=>字符串(29)<p>Jotain mukavaa.</p>"[3]=>整数(12)[4]=>整数(1270929600)}[1]=>数组(5){[0]=>字符串(7)jannala"[1]=>字符串(10)2009-11-16"[2]=>字符串(51)<p>Saapumiserä II/09 astuu palvelukseen</p>"[3]=>整数(11)[4]=>整数(1270929600)}...}
我需要做的是根据数组的 [x][4](unix 时间戳值)对数组进行排序.我将如何实现这一目标?
使用比较函数,在本例中它比较数组的 unix 时间戳值:
function compare($x, $y) {如果 ( $x[4] == $y[4] )返回0;否则如果( $x[4] <$y[4] )返回-1;别的返回 1;}
然后使用 usort
功能如下:
usort($nameOfArray, 'compare');
<块引用>
此函数将使用用户提供的比较函数按数组的值对数组进行排序.如果您希望排序的数组需要按某些重要条件排序,则应使用此函数.
取自PHP: usort 手册.
I have this kind of an array
array(5) {
[0]=>
array(5) {
[0]=>
string(7) "jannala"
[1]=>
string(10) "2009-11-16"
[2]=>
string(29) "
<p>Jotain mukavaa.</p>
"
[3]=>
int(12)
[4]=>
int(1270929600)
}
[1]=>
array(5) {
[0]=>
string(7) "jannala"
[1]=>
string(10) "2009-11-16"
[2]=>
string(51) "
<p>Saapumiserä II/09 astuu palvelukseen</p>
"
[3]=>
int(11)
[4]=>
int(1270929600)
}
...
}
What I need to be done is to sort the array based on array's [x][4] (the unix timestamp value). How would I achieve this?
use a compare function, in this case it compares the array's unix timestamp value:
function compare($x, $y) {
if ( $x[4] == $y[4] )
return 0;
else if ( $x[4] < $y[4] )
return -1;
else
return 1;
}
and then call it with using the usort
function like this:
usort($nameOfArray, 'compare');
This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
Taken from PHP: usort manual.
这篇关于在 PHP 中对多维数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!