0
1

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 3 years have passed since last update.

PHPで配列の中身を再帰的に処理するメモ

Posted at

**引数で渡ってくる配列の深さ・要素数などが分からなくても、上層から下層まで全ての要素に対して処理をしたい!**と思った時のメモです。

結論から言えばarray_walk_recursive関数で再帰処理が可能。

どんな処理を適用するかはユーザ定義関数として自分で決められます。

そのユーザ定義関数を静的メソッドとして使う書き方は第二引数で指定しますが、ただの関数であれば関数名を渡してあげるだけでOKです。

使用例
<?php
namespace App\Library;

use Illuminate\Support\Facades\Log;

class LogClass
{
    public static function walkLog($data)
    {
        if (!empty($data['results'])){
            array_walk_recursive($data['results'], ['self','maskLog']);
        }
    }

    public static function maskLog(&$item, $key)
    {
        if (!is_string($item) || mb_strlen($item) <= 8) return;
        $item = mb_substr($item, 0, 8);
        return;
    }
}

参考URL

array_walk_recursive — 配列の全ての要素に、ユーザー関数を再帰的に適用する
PHPの多次元配列で、階層の深さやキー名が毎回異なる場合に、数値または文字列の値のときだけ操作を行うにはどうしたらよいか

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?