Last active
August 29, 2015 14:23
-
-
Save tadasuke/53daf37145dc9635e7bb to your computer and use it in GitHub Desktop.
2次元配列の2次元目の配列の値でソートをする ref: http://qiita.com/tadasuke/items/e7be0d214e02105ab6d8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$array = array( | |
array( | |
'id' => 10, | |
'name' => 'hoge', | |
), | |
array( | |
'id' => 3, | |
'name' => 'fuga', | |
), | |
array( | |
'id' => 20, | |
'name' => 'foo', | |
), | |
array( | |
'id' => 1, | |
'name' => 'bar', | |
), | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sortArrayByKey( &$array, $sortKey, $sortType = SORT_ASC ) { | |
$tmpArray = array(); | |
foreach ( $array as $key => $row ) { | |
$tmpArray[$key] = $row[$sortKey]; | |
} | |
array_multisort( $tmpArray, $sortType, $array ); | |
unset( $tmpArray ); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$array = array( | |
array( | |
'id' => 10, | |
'name' => 'hoge', | |
), | |
array( | |
'id' => 3, | |
'name' => 'fuga', | |
), | |
array( | |
'id' => 20, | |
'name' => 'foo', | |
), | |
array( | |
'id' => 1, | |
'name' => 'bar', | |
), | |
); | |
// そのまま出力 | |
print_r( $array ); | |
// ソート実行 | |
sortArrayByKey( $array, 'id' ); | |
// もう一度出力 | |
print_r( $array ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array | |
( | |
[0] => Array | |
( | |
[id] => 10 | |
[name] => hoge | |
) | |
[1] => Array | |
( | |
[id] => 3 | |
[name] => fuga | |
) | |
[2] => Array | |
( | |
[id] => 20 | |
[name] => foo | |
) | |
[3] => Array | |
( | |
[id] => 1 | |
[name] => bar | |
) | |
) | |
Array | |
( | |
[0] => Array | |
( | |
[id] => 1 | |
[name] => bar | |
) | |
[1] => Array | |
( | |
[id] => 3 | |
[name] => fuga | |
) | |
[2] => Array | |
( | |
[id] => 10 | |
[name] => hoge | |
) | |
[3] => Array | |
( | |
[id] => 20 | |
[name] => foo | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment