Last active
February 17, 2018 06:23
-
-
Save KEINOS/260bdff4f4beb2d5b607bd1045abaff1 to your computer and use it in GitHub Desktop.
PHP の連想配列で最大長の添字(最も長いキー名)順にソートさせる
This file contains 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
<?php | |
// Ref: https://teratail.com/questions/6342 | |
// See work online: https://paiza.io/projects/UKMXJtPKiT4ztJZuaFFl7g | |
// 関数化した方法 | |
function array_sort_longkey($array) | |
{ | |
uksort($array, function ($a, $b) { | |
return (mb_strlen($b) > mb_strlen($a)); | |
}); | |
return $array; | |
} | |
// サンプルデータ | |
$array = [ | |
"いいいいい" => 'iiiii', | |
"イヌ" => 'dog', | |
"ネコ" => 'cat', | |
"あああ" => 'aaa', | |
"ああああ" => 'aaaa' | |
]; | |
// ソート実行 | |
var_dump( array_sort_longkey($array)); | |
// 結果 | |
/* | |
array(5) { | |
["いいいいい"]=> | |
string(5) "iiiii" | |
["ああああ"]=> | |
string(4) "aaaa" | |
["あああ"]=> | |
string(3) "aaa" | |
["イヌ"]=> | |
string(3) "dog" | |
["ネコ"]=> | |
string(3) "cat" | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment