Ginqのwhereの条件に変数を使いたい
最近、不本意ながらPHPでプログラムを書いている。
PHPの配列、めっちゃ辛いじゃん。Linq使いたい。Linqが使いたいんだー。
と思っていたところ、こんな素敵なライブラリがあるのを発見。
すごく便利そう。
早速つかってみたのですが、whereで変数が使えないのです。
まずはOKパターンから
$result = Ginq::from(array(1,2,3,4,5,6,7,8,9,10)) ->where(function($x) { return $x % 2 != 0; }); var_dump($result->toArray());
出力はこれ。しゅごい。
array(5) { [0]=> int(1) [2]=> int(3) [4]=> int(5) [6]=> int(7) [8]=> int(9) }
NGパターンから
$param = 2; $result = Ginq::from(array(1,2,3,4,5,6,7,8,9,10)) ->where(function($x) { return $x % $param != 0; }); var_dump($result->toArray());
出力はこれ。・・・・Undefined !!!
Undefined variable: param
フォーカス違うもんな・・。しょうがない。
でも、これでは便利に使えない。
どうしよう。
こうしてみた
$param = 2; if (!function_exists('create_where_predicate')) { function create_where_predicate($param) { return function($x) use ($param){ return $x % $param != 0; }; } } $where_predicate = create_where_predicate($param); $result = Ginq::from(array(1,2,3,4,5,6,7,8,9,10)) ->where($where_predicate); var_dump($result->toArray());
できた。
array(5) { [0]=> int(1) [2]=> int(3) [4]=> int(5) [6]=> int(7) [8]=> int(9) }
もっといい方法はないものか・・。
使い方まちがってるのか?
2017/12/22 追記
他の方法があった。。useってのが使えるらしい。
$param = 2;
$result = Ginq::from(array(1,2,3,4,5,6,7,8,9,10))
->where(function($x) use($param) { return $x % $param != 0; });
だいぶすっきりした。