Sort the elements of the array by specifying the conditions

#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

Sort the elements of the array by specifying the conditions
Sort by specifying conditions in CASTable
Sort of tuple array can be accelerated by specifying key (Python)
How to sort by specifying a column in the Python Numpy array.
[python] How to sort by the Nth Mth element of a multidimensional array
Sort tuple list in Python by specifying the ascending / descending order of multiple keys
How to extract conditions (acquire all elements of Group that satisfy the conditions) for Group by Group
Sort the string array in order of length & Japanese syllabary
[Python3] Call by dynamically specifying the keyword argument of the function
I want to judge the authenticity of the elements of numpy array
[Python] Sort iterable by multiple conditions
[Python] Display only the elements of the list side by side [Vertical, horizontal]
[Python] How to use the for statement. A method of extracting by specifying a range or conditions.
[OpenCV] About the array returned by imread
Install by specifying the version with pip
Read the file by specifying the character code.
Pandas of the beginner, by the beginner, for the beginner [Python]
Follow back by specifying conditions using tweepy
Import by directly specifying the directory path
[Python] Combine all the elements in the array
Set the number of elements in a NumPy one-dimensional array to a power of 2 (0 padded)
Checklist on how to avoid turning the elements of numpy's array with for
Get the last element of the array by splitting the string in Python and PHP
Check the operation of OpenCV3 installed by Anaconda
[python] Check the elements of the list all, any
[Python] Sort the list of pathlib.Path in natural sort
Specifying the range of ruby and python arrays
[Python] Sort the table by sort_values (pandas DataFrame)
BeautifulSoup trick: Decide the Tag by specifying the path
The shape of the one-dimensional array of numpy was complicated
Minimize the number of polishings by combinatorial optimization
Judging the finish of mahjong by combinatorial optimization
[Python numpy] Dynamically specify the index of the array
Output in the form of a python array
Search by the value of the instance in the list
[Python] Manipulating elements in a list (array) [Sort]
Sort files updated within the period specified by the find command in order of size
Sort by pandas
Extract the status code error in the 400,500 range of the apache access log by specifying the time range.
Gradually display the output of the command executed by subprocess.Popen
Optical Flow, the dynamics of images captured by OpenCV
The story of Hash Sum mismatch caused by gcrypto20
Get the image of "Suzu Hirose" by Google image search.
○○ Solving problems in the Department of Mathematics by optimization
Python3 datetime is faster just by specifying the timezone
I compared the identity of the images by Hu moment
[Statistics] Understand the mechanism of Q-Q plot by animation.
[Python] Manipulation of elements in list (array) [Add / Delete]
What is the true identity of Python's sort method "sort"? ??
[Golang] Specify an array in the value of map
Get the size (number of elements) of UnionFind in Python
Access Github by specifying the SSH key in GitPython
[Python] Outputs all combinations of elements in the list
Group by consecutive elements of a list in Python
[Django 2.2] Sort and get the value of the relation destination
Play music by hitting the unofficial API of Google Play Music
Convert elements of numpy array from float to int
The copy method of pandas.DataFrame is deep copy by default
Create a 2D array by adding a row to the end of an empty array with numpy