【CakePHP】1人前のケーキ職人になるまで

パティシエじゃないよエンジニアだよ

【CakePHP】Hashクラス

cakeで配列を扱うときに、ハッシュクラスが便利だと出てきたのでメモです。

例えば

Array
(
    [Servant] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => 織田信長
                    [type] => Buster
                )

            [1] => Array
                (
                    [id] => 2
                    [name] => 沖田総司
                    [type] => Quick
                )

            [2] => Array
                (
                    [id] => 3
                    [name] => マーリン
                    [type] => Arts
                )

            [3] => Array
                (
                    [id] => 4
                    [name] => ギルガメッシュ
                    [type] => Buster
                )

        )

)

こういう配列があったとして、

「idが4のサーヴァントを取り出したい時」、

print_r( Hash::extract( $data, 'Servant.{n} [id=4]')); 

としてあげれば配列からデータを取り出してあげることができます。

条件式で指定したデータの配列を生成したい時

例えば、バスタータイプのサーヴァントを配列に入れるとします。 その場合は

print_r( Hash::combine( $data, 
        'Servant.{n}[type=Buster].id', 
        'Servant.{n}[type=Buster].name'
    )
);

とすることで欲しい配列が返ってきます。
phpでarray_searchとかarray_key_existsとか多用する人は特に便利ですね。

<参考にしたサイト>
qiita.com

www.mikame.net