LoginSignup
15
16

More than 5 years have passed since last update.

JSONな配列を、指定の項目でソートをかける、PHPとRuby比較

Posted at

よくあるんだか、ないんだか分からないけど、連想配列とかで特定の値を元にソートをかけたい時がありますよと。そんな時、PHPとRubyだとどんな書き方の違いになるのか比較してみた。ちなみに、普通の配列じゃなくてJSONからやっているのは、特に意味はない。

例えば、こんな感じのJSONがあったとして、idの値で降順にソートしたい…。なにがなんでもしたい。という場合。特に外部ライブラリなど使わず普通に言語の機能として書ける方法。

json
[
    {
        "id": 1,
        "title": "title1"
    },
    {
        "id": 3,
        "title": "title3"
    },
    {
        "id": 2,
        "title": "title2"
    }
]

PHPでソート

PHP5.3以降であればクロージャが使えるので、usortが少しは楽に書くことが出来る。でも、usortは破壊的メソッドなので、使い勝手が悪い瞬間があるな…。

php
<?php
    $jsonStr = <<<EOM
[
    {
        "id": 1,
        "title": "title1"
    },
    {
        "id": 3,
        "title": "title3"
    },
    {
        "id": 2,
        "title": "title2"
    }
]
EOM;

    $json = json_decode($jsonStr);

    // idの値、降順でソート
    usort($json, function ($a, $b) {
        if ($a->id == $b->id) return 0;
        return ($a->id > $b->id) ? -1 : 1;
    });

    var_dump($json);
php結果
array(3) {
  [0]=>
  object(stdClass)#2 (2) {
    ["id"]=>
    int(3)
    ["title"]=>
    string(6) "title3"
  }
  [1]=>
  object(stdClass)#3 (2) {
    ["id"]=>
    int(2)
    ["title"]=>
    string(6) "title2"
  }
  [2]=>
  object(stdClass)#1 (2) {
    ["id"]=>
    int(1)
    ["title"]=>
    string(6) "title1"
  }
}

Rubyでソート

Rubyは、sort_byでブロック使ってソートが可能。記述量も少ない。わりと覚えやすいと思う。

Ruby
require 'json'

jsonStr = <<"EOM"
[
    {
        "id": 1,
        "title": "title1"
    },
    {
        "id": 3,
        "title": "title3"
    },
    {
        "id": 2,
        "title": "title2"
    }
]
EOM

json = JSON.parse(jsonStr)

# idの値、降順でソート
p json.sort_by { |hash| -hash['id'].to_i }

# idの値、昇順でソート
p json.sort_by { |hash| hash['id'].to_i }

Ruby結果
[{"id"=>3, "title"=>"title3"}, {"id"=>2, "title"=>"title2"}, {"id"=>1, "title"=>"title1"}]
[{"id"=>1, "title"=>"title1"}, {"id"=>2, "title"=>"title2"}, {"id"=>3, "title"=>"title3"}]
15
16
1

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
15
16