Skip to content

Commit

Permalink
修改 Arr::map
Browse files Browse the repository at this point in the history
  • Loading branch information
webguosai committed Sep 27, 2022
1 parent f8bb192 commit c40341e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 31 deletions.
30 changes: 12 additions & 18 deletions src/Helper/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
25 changes: 12 additions & 13 deletions tests/test.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down

0 comments on commit c40341e

Please sign in to comment.