
実務で良くあるアルゴリズム🐱
もくじ
こういうのとか
$users = [
[
'id' => 1,
'email' => '1@example.com',
'profile_enable' => true,
],
[
'id' => 2,
'email' => '2@example.com',
'profile_enable' => false,
],
[
'id' => 3,
'email' => '3@example.com',
'profile_enable' => true,
],
];
$user_profiles = [
[
'id' => 1,
'user_id' => 1,
'name' => "優さん",
],
[
'id' => 2,
'user_id' => 2,
'name' => "佐藤",
],
[
'id' => 3,
'user_id' => 3,
'name' => "鈴木",
],
];
// 子を親のidでindexを指定して配列化
$profile_contents = [];
foreach ($user_profiles as $user_profile) {
$profile_contents[$user_profile['user_id']] = $user_profile;
}
// 親のプロフィール設定が有効であれば出力
foreach ($users as $user) {
if ($user['profile_enable']) {
print_r($profile_contents[$user['id']]);
}
}
// Array
// (
// [id] => 1
// [user_id] => 1
// [name] => 優さん
// )
// Array
// (
// [id] => 3
// [user_id] => 3
// [name] => 鈴木
// )
数が大きくなった重い処理を解消をする時に使える
public function getUsersSkillNames()
{
$users = Users->all();
$user_skill_names = [];
foreach ($users as $user) {
$user_profile = userProfile->where('user_id', $user->id);
foreach($user_profile->skill_ids as $skill_id) {
$user_skill_names[$user->id][] = Skill->where('id', $skill_id)->name;
}
}
return $user_skill_names;
}
のようなn+1 な状況
解決する
連想配列で処理できるようにする
public function getUsersSkillNames()
{
$skills = Skill->all();
foreach ($skill_arrays as $skill) {
$skill_names[$skill_id] = $skill->name;
}
$user_skill_ids = User::with('profiles')->pluck('skill_ids', 'user_id')->get()->toArray();
// ここはすべて配列で処理できる
$user_skill_names = [];
foreach ($user_skill_ids as $user_id => $skill_ids) {
foreach ($skill_ids as $skill_id) {
$user_skill_names[$user->id][] = $skill_names[$skill_id]
}
}
return $user_skill_names;
}
利用イメージ
$users_skill_names = $this->getUserSkillNames();
$guest_users = User->where('type', 'guest')->get();
foreach ($guest_users as $guest_user) {
$user_skill_names = isset($user_skill_names[$guest_user->id]) ?? [];
}
解消できる🐱







広告じゃまくさいしインタフェースが良くないブログだと思います。
ご意見有難う御座います!
シンプルで見やすいサイトだと思います。
広告についてもAdblock使えばいいだけなので問題ないです。
応援しています。
有難う御座います!
広告料金で維持費を賄っているので。
良い広告があれば見てあげてください🐱✨