★Javascript
// 連想配列を定義
var arrays = new Array(
{title: "Safari", date: 2003},
{title: "Firefox", date: 2002},
{title: "Opera", date: 1995},
{title: "Chrome", date: 2008});
// "date" をキーに降順に並び替える
arrays.sort(function(a, b) {return a["date"] < b["date"] ? 1 : -1;});
// "date" をキーに昇順に並び替える
arrays.sort(function(a, b) {return a["date"] > b["date"] ? 1 : -1;});
var arrays = new Array(
{title: "Safari", date: 2003},
{title: "Firefox", date: 2002},
{title: "Opera", date: 1995},
{title: "Chrome", date: 2008});
// "date" をキーに降順に並び替える
arrays.sort(function(a, b) {return a["date"] < b["date"] ? 1 : -1;});
// "date" をキーに昇順に並び替える
arrays.sort(function(a, b) {return a["date"] > b["date"] ? 1 : -1;});
★php
// 連想配列を定義
$arrays = array(
array("title" => "Safari", "date" => 2003),
array("title" => "Firefox", "date" => 2002),
array("title" => "Opera", "date" => 1995),
array("title" => "Chrome", "date" => 2008));
// "date" をキーに降順に並び替える
function cmp($a, $b) {return $a["date"] < $b["date"] ? 1 : -1;}
usort($arrays, "cmp");
// "date" をキーに昇順に並び替える
function rcmp($a, $b) {return $a["date"] > $b["date"] ? 1 : -1;}
usort($arrays, "rcmp");
$arrays = array(
array("title" => "Safari", "date" => 2003),
array("title" => "Firefox", "date" => 2002),
array("title" => "Opera", "date" => 1995),
array("title" => "Chrome", "date" => 2008));
// "date" をキーに降順に並び替える
function cmp($a, $b) {return $a["date"] < $b["date"] ? 1 : -1;}
usort($arrays, "cmp");
// "date" をキーに昇順に並び替える
function rcmp($a, $b) {return $a["date"] > $b["date"] ? 1 : -1;}
usort($arrays, "rcmp");
php では usort() と一緒に使わないといけないのがめんどくさいが、ほぼ同じような感じでいけるので混乱はまぁない。降順・昇順は < と > を変えるだけ。
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.