#PHP 5.4.9
<?php
$ary = array(
array('name'=>'aaa','age'=>111,'id'=>1),
array('name'=>'bbb','age'=>555,'id'=>2),
array('name'=>'ccc','age'=>222,'id'=>3)
);
function cmp_by_key($k){
$cmp = function($a,$b)use($k) {
if($a[$k] == $b[$k]){
return 0;
}elseif($a[$k] < $b[$k]){
return -1;
}else{
return 1;
}
};
return $cmp;
}
#order by age
echo 'order by age'.PHP_EOL;
$by_age = cmp_by_key('age');
usort($ary,$by_age);
foreach($ary as $k => $v ){
echo str_replace(PHP_EOL,'',var_export($v,true)).PHP_EOL;
}
#order by id
echo 'order by id'.PHP_EOL;
$by_id = cmp_by_key('id');
usort($ary,$by_id);
foreach($ary as $k => $v ){
echo str_replace(PHP_EOL,'',var_export($v,true)).PHP_EOL;
}
/* output
order by age
array ( 'name' => 'aaa', 'age' => 111, 'id' => 1,)
array ( 'name' => 'ccc', 'age' => 222, 'id' => 3,)
array ( 'name' => 'bbb', 'age' => 555, 'id' => 2,)
order by id
array ( 'name' => 'aaa', 'age' => 111, 'id' => 1,)
array ( 'name' => 'bbb', 'age' => 555, 'id' => 2,)
array ( 'name' => 'ccc', 'age' => 222, 'id' => 3,)
*/
#Python 2.7.1
data =[
{'name':'aaa','age':111,'id':1},
{'name':'bbb','age':555,'id':2},
{'name':'ccc','age':222,'id':3}]
print "order by age"
for row in sorted(data,key=lambda x:x['age']):
print row
print "order by id"
for row in sorted(data,key=lambda x:x['id']):
print row
order by age
""" output
{'age': 111, 'name': 'aaa', 'id': 1}
{'age': 222, 'name': 'ccc', 'id': 3}
{'age': 555, 'name': 'bbb', 'id': 2}
order by id
{'age': 111, 'name': 'aaa', 'id': 1}
{'age': 555, 'name': 'bbb', 'id': 2}
{'age': 222, 'name': 'ccc', 'id': 3}
"""
//scala 2.10.1
var data = List(
Map("name"->"aaa","age"->"111","id"->"1"),
Map("name"->"bbb","age"->"555","id"->"2"),
Map("name"->"ccc","age"->"222","id"->"3"))
//order by age
var by_age = data.sortBy( a=>a("age").toInt )
println("order by age")
by_age.foreach(println)
//order by id
var by_id = data.sortBy( a=>a("id").toInt )
println("order by id")
by_id.foreach(println)
/* output
order by age
Map(name -> aaa, age -> 111, id -> 1)
Map(name -> ccc, age -> 222, id -> 3)
Map(name -> bbb, age -> 555, id -> 2)
order by id
Map(name -> aaa, age -> 111, id -> 1)
Map(name -> bbb, age -> 555, id -> 2)
Map(name -> ccc, age -> 222, id -> 3)
*/
Recommended Posts