4
5

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.

【CakePHP】Hash

Last updated at Posted at 2015-04-15

一旦投稿。随時加筆予定。

配列の操作に大活躍。
Setも同様の機能を持っているけど、2.2以降Hashが推奨。

以下のfind('all')の結果を対象に配列操作してみたい。

$results = array(
  0 => array(
    'Book' => array(
      'id'=>17,
      'title' => 'CODE COMPLETE 第2版',
      'auther' => 'スティーブマコネル',
    )
  ),
  1 => array(
    'Book' => array(
      'id'=>19,
      'title' => '新装版 リファクタリング',
      'auther' => 'Martin Fowler',
    )
  )
);

配列を作る

例えば、本のタイトルだけで配列を作りたいとき。

$book_list = Hash::extract($results, '{n}.Book.title');
var_dump($book_list);

/*
array(2) {
  [0]=>
  string(1) "CODE COMPLETE 第2版"
  [1]=>
  string(1) "新装版 リファクタリング"
}
*/

連想配列を作る

セレクト用のidとtitleの組合せを作る場合。ただこれならfind('list')でも良い。

$book_list = Hash::combine($results, '{n}.Book.id','{n}.Book.title');
var_dump($book_list);

/*
array(2) {
  [17]=>
  string(1) "CODE COMPLETE 第2版"
  [19]=>
  string(1) "新装版 リファクタリング"
}
*/

参考
CakePHPのarray地獄をHashクラスで生きのこる
【cakePHP】配列を組み替える便利なHashクラス

4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?