[PHP] 配列を日付・時間の新しい順に並び替える

2006年11月07日 火曜日 12時11分
E-Mail This Post/Page Print This Post/Page

php での配列のソートには usort() が使えます。例えば以下のような日付を含む配列があるとします。

$data = array (
   array("2006-11-11", 'apple'),
   array("2006-11-21", 'banana'),
   array("2006-10-31", 'orange'),
   array("2006-10-01", 'melon')
);

これを、

usort($data, "sort_date");
 
function sort_date($A, $B){
  $b=$A[2];
  $a=$B[2];
 
  if ($a == $b) {
  return 0;
  }
  return ($a < $b) ? -1 : 1;
}

とするともっとも新しい日付のエレメントが前に配置されます。

ではソートする配列が日付だけでなく時間の情報を持っている場合はどうなるでしょうか。

$data = array (
   array("2006-11-11 15:02", 'apple'),
   array("2006-11-11 21:11", 'banana'),
   array("2006-11-11 01:23", 'orange'),
   array("2006-11-11 03:21", 'melon')
);

この場合は以下の関数が便利です。

function sort_time($B, $A) {
    return strtotime($A[0]) - strtotime($B[0]);
}

ですので、実際には

usort($data, "sort_time");

のように使用することになります。

この記事に関連する NEWS

この記事に関連するトピック

このエントリーへの Yahoogle Suggestions

Trackback this Post |

 

記事ヒット TOP 10

IT 関連 NEWS

    There is no entries available for this category.

PHP関連 NEWS

    There is no entries available for this category.

PHP Tips from Social Bookmarks

    There is no entries available for this category.

PHPに関するフォーラムトピック

    There is no entries available for this category.

Tag Cloud

admin Admin Drop Menus Admin Memo Admin Panel advanced drop menus array unique blog cron dabeya Dagon Design Sitemap Generator dropcap Edit N Place error Feedburner game google hack html HTML CSS Internet NEWS Permalink Redirect PHP phpBB2 plugin RSS scripts search stattraq template the content Ultimate Tag Warrior Web Management Windows XP Wordpress WP Plugins WPページ  拡張子 カスタマイズ カスタム関数 カテゴリー コード セキュリティ タグ トップページ トラックバック フィード 投稿 抜粋 日本語 時刻 時間 正規表現 表示 記事

サイト メニュー

Blogtimes image
ぱそずき :D)‐く © 2008
Close
E-mail It