1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

phpの並び替えで空の値を最後に持ってきたいときの書き方

1
Posted at

どうしてもPHP側でデータの並び替えをしないといけなかったので、usortを使ってみた。

やりたいこと

メールアドレスを昇順かつ空のときには末尾に持ってくる。

やってみた

usortで下記のソースを書くと、期待通りに並べ替えられた。

$data = array(
    '1'  => '',
    '2'  => 'sample@example.com', 
    '3'  => 'hoge@example.com',
);

usort($data, function ($left, $right) {
    $leftHoge  = mb_strtolower($left['mail']); // 小文字に統一
    $rightHoge = mb_strtolower($right['mail']);
    if (empty($leftHoge)) {
        return 1;
    }
    if (empty($rightHoge)) {
        return -1;
    }
    if ($leftHoge < $rightHoge) {
        return -1;
    } else if ($leftHoge > $rightHoge) {
        return 1;
    }
});

var_dump($data);

// $data = array(
    '1'  => 'hoge@example.com',
    '2'  => 'sample@example.com', 
    '3'  => '',
);

1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?