tag:crieit.net,2005:https://crieit.net/tags/array_filter/feed
「array_filter」の記事 - Crieit
Crieitでタグ「array_filter」に投稿された最近の記事
2022-05-18T00:05:39+09:00
https://crieit.net/tags/array_filter/feed
tag:crieit.net,2005:PublicArticle/18192
2022-05-18T00:05:39+09:00
2022-05-18T00:05:39+09:00
https://crieit.net/posts/php-operating-array-closure-20220519
PHP の array_filter() で条件に一致した配列の要素を抽出する
<p>PHP で array.filter のようなことをしたくなったのでメモ。</p>
<h2 id="コード"><a href="#%E3%82%B3%E3%83%BC%E3%83%89">コード</a></h2>
<pre><code class="php"><?php
declare(strict_types=1);
function getEmployeeList(string $dept_name): array
{
return array_values(
array_filter(
$employees,
function($employee) use ($dept_name) {
return $employee->getDeptName() === $dept_name;
}
)
);
}
</code></pre>
<p>イメージとしてこのような感じで意図した挙動になることを確認しました。</p>
<p>やっていることととしては、「ある部署に所属する (部署名 <code>$dept_name</code> で抽出) 社員全員の一覧」を抽出しています。</p>
<p>なお、前提として社員データの配列 <code>$employees</code> (各要素が予め定義された <code>Employee</code>オブジェクト) があるものとしています。</p>
<p>ところで、この形 Eloquent の複合条件抽出でも見かけました……そう、 <code>array_filter()</code> の第二引数(コールバック関数)がクロージャで、スコープを越えて外部変数を使うために <code>use</code>句 を用いる、という形がそっくりそのままですね。</p>
<p>デジャヴも良いところですね。</p>
<h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2>
<h3 id="arra_values()"><a href="#arra_values%28%29">arra_values()</a></h3>
<ul>
<li><a target="_blank" rel="nofollow noopener" href="https://www.php.net/manual/ja/function.array-values.php">PHP: array_values - Manual</a></li>
</ul>
<h3 id="array_filter()"><a href="#array_filter%28%29">array_filter()</a></h3>
<ul>
<li><a target="_blank" rel="nofollow noopener" href="https://www.php.net/manual/ja/function.array-filter.php">PHP: array_filter - Manual</a></li>
<li><a target="_blank" rel="nofollow noopener" href="https://kimagureneet.hatenablog.com/entry/2017/03/07/003958">【php】配列を複数条件で検索、絞り込みする方法メモ - とりあえずphpとか</a></li>
<li><a target="_blank" rel="nofollow noopener" href="https://wani-pro.com/func-array_filter/">【php】 配列を条件で絞り込む(array_filter) - わにプログラミング</a></li>
</ul>
arm-band