LoginSignup
8
1

More than 3 years have passed since last update.

-1, 0, 1, 2, 3, ... , nullの順にソートしたかった話

Posted at

やりたかったこと

Laravelで

$array = [null, 1.5, 1.0, 0.5, 0, -1.0];

のような配列を

[-1.0, 0, 0.5, 1.0, 1.5, null]

のように数値は昇順にしつつ、nullを最後に持っていきたかった。

JavaScriptなら

let arr = [null, 1.5, 1.0, 0.5, 0, -1.0];
console.log(arr.sort()); // [-1, 0, 0.5, 1, 1.5, null]

sort()を使えば良いようだ。

環境

  • PHP 7.2.16
  • Laravel 5.5.45

やってみる

$collection = collect([null, 1.5, 1.0, 0.5, 0, -1.0]);

Laravelなので、配列をコレクションにして取り扱うことにする。

$sorted = $collection->sort()->values();

sort()メソッドを使ってみるが、

// $sortedの中身
=> Illuminate\Support\Collection {
     all: [
       null,
       -1.0,
       0,
       0.5,
       1.0,
       1.5,
     ],
   }

nullが最初に来てしまう・・・。

こうしてみた

$sorted = $collection->sortBy(function($item){
    return $item === null ? PHP_FLOAT_MAX : $item;
})->values();

sortBy()は指定したキーでソートしてくれる。
関数を渡し、それをもとにソートさせることも可能だ。

PHP_FLOAT_MAXはPHP7.2.0から登場し、浮動小数点の数値として最大を表す。

これらを利用し、コレクション中のnullを最大値として見せかけることにした。

// $sortedの中身
=> Illuminate\Support\Collection {
     all: [
       -1.0,
       0,
       0.5,
       1.0,
       1.5,
       null,
     ],
   }

作戦成功。

数値は昇順に並びつつ、nullが最後に来てくれた。

8
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
1