From c40341e7feeea2ae0cd39706c64928b5d0fea27f Mon Sep 17 00:00:00 2001 From: Json <501807312@qq.com> Date: Tue, 27 Sep 2022 18:03:53 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20Arr::map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Helper/Arr.php | 30 ++++++++++++------------------ tests/test.php | 25 ++++++++++++------------- 2 files changed, 24 insertions(+), 31 deletions(-) diff --git a/src/Helper/Arr.php b/src/Helper/Arr.php index 45b8bf0..6a67c47 100644 --- a/src/Helper/Arr.php +++ b/src/Helper/Arr.php @@ -180,35 +180,29 @@ public static function random(array $array) } /** - * 数组映射 (目前只支持一维) - * $array = ['name1' => '111'] - * $table = ['name1' => 'name'] - * 映射后 ['name' => '111'] + * 增强原生 array_map 支持key * - * @param array $array 要映射的数组 - * @param array $table 要映射的对应表 - * @param bool $convertEmpty 将null等空内容,转换为'' + * @param callable $callable 回调函数 + * @param array $array 数组 * @return array */ - public static function map(array $array, array $table, $convertEmpty = true) + public static function map(callable $callable, array $array) { - $keys = array_keys($table); + $map = []; - $new = []; foreach ($array as $key => $value) { + $result = $callable($key, $value); - if ($convertEmpty && empty($value) && is_string($value)) { - $value = ''; - } - - if (in_array($key, $keys)) { - $new[$table[$key]] = $value; + if (is_array($result)) { + $map[key($result)] = $result[key($result)]; + } elseif (is_string($result)) { + $map[$key] = $result; } else { - $new[$key] = $value; + $map[$key] = $value; } } - return $new; + return $map; } /** diff --git a/tests/test.php b/tests/test.php index 0ed9f4d..5233187 100644 --- a/tests/test.php +++ b/tests/test.php @@ -340,20 +340,19 @@ /** 数组映射 **/ //$arr = [ -// 'name1' => '111', -// 'sex1' => '男', -// 'job1' => null, -// 'age' => null, -// 'other1' => [], -// 'other2' => [1,2,3], +// 'sai', +// 'dan', //]; -//$table = [ -// 'name' => 'name1', -// 'job' => 'job1', -// 'sex' => 'sex1', -//]; -// -//dd(Arr::map($arr, $table)); +//$data = Arr::map(function ($key, $value) { +// // 返回字符串,不会修改key +//// return $value; +// // 返回数组,会修改key +//// return [ +//// $value => strtoupper($value), +//// ]; +//}, $arr); +//dump($data); + //dd(Arr::implode([1,2,3,4,5])); //dd(Str::explode('1,2,3,4')); //dd(substr_replace('中文啊12345678', '****', 3, 4));