在 PHP 中对多维数组进行排序? [英] Sorting a multidimensional array in PHP?

查看:51
本文介绍了在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆