LoginSignup
2
2

Laravel初心者向け、よく使うCollectionの整形系メソッド

Posted at

概要

自分が普段仕事で良く使うCollectionのデータ整形系メソッドを抜粋して紹介します。
EloquentCollection特有のメソッドは除外しています

一覧

map

mapメソッドは、クロージャを利用して、各要素を整形します。

$people = collect([
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25],
    ['name' => 'Doe', 'age' => 30],
]);

// 各人の名前を大文字に変換して新しいコレクションを作成
$uppercasedNames = $people->map(function ($person) {
    return [
        'name' => strtoupper($person['name']),
        'age' => $person['age']
    ];
});

dd($uppercasedNames->all());

// 結果:
//array:3 [▼ 
//  0 => array:2 [▼
//    "name" => "JOHN"
//    "age" => 30
//  ]
//  1 => array:2 [▼
//    "name" => "JANE"
//    "age" => 25
//  ]
//  2 => array:2 [▼
//    "name" => "DOE"
//    "age" => 30
//  ]
//]

mapWithKeys

mapWitKeysメソッドは、クロージャを利用して各要素のキーと値を整形します。

$people = collect([
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25],
    ['name' => 'Doe', 'age' => 30],
]);

// 名前をキー、年齢を値とする連想配列を作成
$keyedData = $people->mapWithKeys(function ($person) {
    return [$person['name'] => $person['age']];
});

dd($keyedData->all());

// 結果:
//array:3 [▼ 
//  "John" => 30
//  "Jane" => 25
//  "Doe" => 30
//]

flatten

flattenメソッドは、どのような多次元の配列であればフラットな配列に整形します。

$nestedArray = collect([
    ['John', 'Jane', 'Doe', 'colors' => ['orange', 'black', 'white']],
    ['PHP', 'Laravel', 'JavaScript'],
    [30, 25, 30],
]);

// 多次元の配列をフラットな配列に変換
$flattenedArray = $nestedArray->flatten();
dd($flattenedArray->all());

// 結果:
//array:12 [▼ // app/Filament/Pages/Dashboard.php:33
//  0 => "John"
//  1 => "Jane"
//  2 => "Doe"
//  3 => "orange"
//  4 => "black"
//  5 => "white"
//  6 => "PHP"
//  7 => "Laravel"
//  8 => "JavaScript"
//  9 => 30
//  10 => 25
//  11 => 30
//]

flatMap

flatMapメソッドは、flattenメソッド と mapメソッド を合体させたようなメソッドで、
クロージャを利用して整形した要素を、フラットな配列に変換します。

$people = collect([
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25],
    ['name' => 'Doe', 'age' => 30],
]);

// 各人の年齢を2倍にして1つのコレクションにまとめる
$flatPeople = $people->flatMap(function ($person) {
    return [$person['name'], $person['age'] * 2];
});

dd($flatPeople->all());

// 結果: 
//array:6 [▼ // app/Filament/Pages/Dashboard.php:36
//  0 => "John"
//  1 => 60
//  2 => "Jane"
//  3 => 50
//  4 => "Doe"
//  5 => 60
//]

実際に書くようなコード

DevelopmentApprovalオブジェクトが羅列されている

$this->projects->flatMap(function(Development $development){
    return $development->developmentApprovals);
});

// DevelopmentApprovalモデルオブジェクトが羅列されている一次元配列が出来上がる
2
2
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
2
2