1.array_map(为数组的每个元素应用回调函数)


$arr = ['lanting','nanfeng','xuehua','xiao'];
$result = array_map(function($item){ return strtoupper($item);},$arr);


$info = array_keys($data);
$data = array_flip($info);
$result =  array_map(function ($item) {
    return $item + 1;
}, $data);


$arr1=array(1,3,5,7);
$arr2=array(2,4,6,8,9);
$results=array_map(function($a,$b){
    return $a*$b;
},$arr1,$arr2);

2.array_walk(使用用户自定义函数对数组中的每个元素做回调处理)

        //array_walk,array_map实现同一个效果
        $arr = ['lanting','nanfeng','xuehua','xiao'];
        //使用array_map
        $result = array_map(function($item){ return strtoupper($item);},$arr);
        //使用array_walk
        array_walk($arr,function(&$item){$item = strtoupper($item);return $item;});

array_map和array_walk的区别:
1.array_map第一个参数是回调,array_walk第二个参数是回调。
2.array_map可以处理多个一维数组(多参数),array_walk可以处理多维数组(二维数组)(只有2个参数)。
3.array_map有返回值,array_walk使用&直接操作原数组,返回值是bool型。
4.array_map操作数组的值没有key,array_walk可以操作数组的key,value。

      $arr = [
            1 => ['name' => 'lanting', "code" => 100],
            2 => ['name' => 'shanghai', "code" => 200],
            3 => ['name' => 'beijing', "code" => 100],
        ];
        array_walk($arr, function ($value, $key) use (&$arr) {
            if ($value['code'] == 100) {
                $arr[$key] = $value['name'];
            } else {
                unset($arr[$key]);
            }
        });

结果:array:2 [
  1 => "lanting"
  3 => "beijing"
]

       

3.array_walk_recursive( 对数组中的每个成员递归地应用用户函数)

        $array = [1 => [2, 5 => [4, 2], [7, 8 => [3, 6]], 5], 4];
        global $arr;
        $arr = [];
        array_walk_recursive($array, function ($k) {
            global $arr;
            $arr[] = $k;
        });
        // $arr=[2,4,2,7,3,6,5,4]

4.usort自定义排序

//https://www.cnblogs.com/leekale/p/4662736.html
usort两两提取数组中的数值,并按顺序输入自定义函数中,自定义函数根据内容返回1或者-1;usort根据返回值为1或者-1,得到传入的数值1“大于”或者“小于”数值2,然后对数值进行从小到大的排序。即:返回值为1,说明数值1“大于”数值2,然后排序:数值2—>数值1;返回值为-1,说明数值1“小于”数值2,然后排序:数值1->数值2。

上面自定义函数中,$a<$b如果正确返回1,说明$a"大于"$b,则按照顺序$b->$a来排序;如果错误返回-1,说明说明$a"小于"$b,则按照顺序$a->$b来排序。

$arr = [15, 646, 46, 79, 19, 84, 451, 27, 99];
        usort($arr, function ($str1, $str2) {
            return $str1 > $str2 ? 1 : -1;  //从小到大
        });
       

//需求:对一个数组先奇后偶,然后再进行从大到小排序。
//实现步骤为:
//1.判断输入的两个值是否都为偶数,都为偶数,进行从大到小排序;
//2.如果不都为偶数,则至少一个为奇数,先判断$str1是否为偶数,如果为偶数,即:if($str1%2==0)成立,则返回1,意味着$str1“大于”$str2,则usort函数进行排序为“小的”$str2->“大的”$str1(偶数);
//3.如果$str1为奇数,上面不返回任何值,接着判断$str2是否为偶数,如果为偶数,则返回-1,意味着$str1“小于”$str2,则usort函数进行排序为“小的”$str1(奇数)->“大的”$str2(偶数);
//4.如果两个值都为奇数,则上面不返回任何值,接着对$str1和$str2进行从大到小排序;

        $arr = [15, 646, 46, 79, 19, 84, 451, 27, 99];
        usort($arr, function ($str1, $str2) {
            if ($str1 % 2 == 0 && $str2 % 2 == 0) {
                return $str1 < $str2 ? 1 : -1;
            }
            if ($str1 % 2 == 0) {
                return 1;
            }
            if ($str2 % 2 == 0) {
                return -1;
            }
            return $str1 < $str2 ? 1 : -1;
        });
    }
//需求:根据法律合规/标准合规排序后,再根据风险等级由高到低排序
$dangerLevel= [
  "serious" => 0
  "high" => 1
  "middle" => 2
  "low" => 3
  "none" => 4
];
$complyType= [
  "law" => 0
  "standard" => 1
  "diff" => 2
];
$result = [
   [
    "desc" => "此处省略100个字"
    "complyType" => "law"
    "dangerType" => "behaviorLost"
    "dangerLevel" => "high"
    "suggestion" => "<p>此处省略100个字</p>"
    "tab" => "purpose"
    "law" => null
    "standard" => null
  ],
  [
    "desc" => "此处省略100个字"
    "complyType" => "law"
    "dangerType" => "systemLost"
    "dangerLevel" => "middle"
    "suggestion" => "此处省略100个字</p>"
    "tab" => "notice"
    "law" => null
    "standard" => null
  ],
  [
    "desc" => "此处省略100个字"
    "complyType" => "law"
    "dangerType" => "behaviorLost"
    "dangerLevel" => "low"
    "suggestion" => "<p>此处省略100个字</p>"
    "tab" => "notice"
    "law" => null
    "standard" => null
  ]
];

usort($result, function ($itemA, $itemB) use ($dangerLevel, $complyType) {
            $dangerLevelA = $dangerLevel[$itemA['dangerLevel']];
            $dangerLevelB = $dangerLevel[$itemB['dangerLevel']];
            $complyTypeA = $complyType[$itemA['complyType']];
            $complyTypeB = $complyType[$itemB['complyType']];
            if ($dangerLevelA == $dangerLevelB && $complyTypeA == $complyTypeB) return 0;
            return $dangerLevelA < $dangerLevelB || $complyTypeA < $complyTypeB ? -1 : 1;
        });

5.extract
extract() 函数从数组中将变量导入到当前的符号表。
该函数使用数组键名作为变量名,使用数组键值作为变量值。针对数组中的每个元素,将在当前符号表中创建对应的一个变量。
该函数返回成功设置的变量数目。

$arr = [
            'lanting' => 'Lanting',
            'nanfeng' => [
                'name' => 'nanfeng',
                'phone' => '15252345524'
            ],
            'name' => [
                'location' => 'shanghai'
            ]
        ];
        /**
         * @var $lanting
         * @var $nanfeng
         * @var $name
         */
        extract($arr);
        dd($lanting, $nanfeng, $name);

6.array_reduce(用回调函数迭代地将数组简化为单一的值)

    $arr = [
            ['min' => 1.5456, 'max' => 2.28548, 'volume' => 23.152],
            ['min' => 1.5457, 'max' => 2.28549, 'volume' => 23.152],
            ['min' => 1.5458, 'max' => 2.28550, 'volume' => 23.152],
            ['min' => 1.5459, 'max' => 2.28551, 'volume' => 23.152],
            ['min' => 1.5460, 'max' => 2.28552, 'volume' => 23.152],
        ];
        $initial = array_shift($arr);
        $result = array_reduce($arr, function ($result, $item) {
            $result['min'] = min($result['min'], $item['min']);
            $result['max'] = max($result['max'], $item['max']);
            $result['volume'] += $item['volume'];
            return $result;
        }, $initial);

        //["min" => 1.5456, "max" => 2.28552, "volume" => 115.76]
        $arr['foo'] = [1, 2, 3];
        $arr['bar'] = [4, 5, 6];
        $result = array_reduce($arr, 'array_merge', []);
        //[1,2,3,4,5,6]
        //生成一个拼接过的字符串
        $test = ['page1', 'page2', 'page3'];
        $result = array_reduce($test, function ($html, $page) {
            $html .= "<tr><td><a href=\"$page.html\">$page</a></td></tr>\n";
            return $html;
        });

7.SplFileInfo(获取文件的信息)

        $path = base_path('mydoc.docx');
        $file = new \SplFileInfo($path);
        dd([
            'getATime' => $file->getATime(), //最后访问时间
            'getBasename' => $file->getBasename(), //获取无路径的basename
            'getCTime' => $file->getCTime(), //获取inode修改时间
            'getExtension' => $file->getExtension(), //文件扩展名
            'getFilename' => $file->getFilename(), //获取文件名
            'getGroup' => $file->getGroup(), //获取文件组
            'getInode' => $file->getInode(), //获取文件inode
//            'getLinkTarget' => $file->getLinkTarget(), //获取文件链接目标文件
            'getMTime' => $file->getMTime(), //获取最后修改时间
            'getOwner' => $file->getOwner(), //文件拥有者
            'getPath' => $file->getPath(), //不带文件名的文件路径
            'getPathInfo' => $file->getPathInfo(), //上级路径的SplFileInfo对象
            'getPathname' => $file->getPathname(), //全路径
            'getPerms' => $file->getPerms(), //文件权限
            'getRealPath' => $file->getRealPath(), //文件绝对路径
            'getSize' => $file->getSize(),//文件大小,单位字节
            'getType' => $file->getType(),//文件类型 file  dir  link
            'isDir' => $file->isDir(), //是否是目录
            'isFile' => $file->isFile(), //是否是文件
            'isLink' => $file->isLink(), //是否是快捷链接
            'isExecutable' => $file->isExecutable(), //是否可执行
            'isReadable' => $file->isReadable(), //是否可读
            'isWritable' => $file->isWritable(), //是否可写
        ]);

8.array_filter

       $data = [
            0 => 'lanting',
            1 => false,
            2 => 24,
            3 => null,
            4 => '',
            5 => '0',
            6 => 0,
        ];
        $result = array_filter($data); //[0 => "lanting",2 => 24]
$data = [
            'a' => 45,
            '1' => 68,
            'lanting' => 99,
            'shanghai' => 24,
            'nanfeng' => 12
        ];
        $result = array_filter($data, function ($val) {
            return $val & 1;//位运算 返回奇数  [ "a" => 45 ,"lanting" => 99]
            return !($val & 1);//位运算 返回偶数  [1 => 68,"shanghai" => 24,"nanfeng" => 12]
        });
$data = [Null, False, 0, ""];
// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter($data, 'strlen'); //    [2 => 0]

$string = "lanting
        zhagnsan
        lanfeng
        haahahah";
        $array = array_filter(array_map('trim', explode("\n", $string)), 'strlen');
//        [
//            0 => "lanting",
//            1 => "zhagnsan",
//            2 => "lanfeng",
//            3 => "haahahah"
//        ];

9 filter_val(过滤器)
可以参考:https://blog.csdn.net/shooke/...

//验证邮箱格式是否正确 正确直接返回邮箱string,错误返回false
$result = filter_var("localpart.ending.with.dot.@example.com",FILTER_VALIDATE_EMAIL);//false(不支持这种格式的验证,还有很多...)

$result = filter_var("768429319.@example.com",FILTER_VALIDATE_EMAIL);

//验证url
$result = filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED);
//FILTER_FLAG_SCHEME_REQUIRED – 要求 URL 是 RFC 兼容 URL。(比如:http://cg.am)
//FILTER_FLAG_HOST_REQUIRED – 要求 URL 包含主机名(比如:http://levi.cg.com)
//FILTER_FLAG_PATH_REQUIRED – 要求 URL 在主机名后存在路径(比如:http://levi.cg.am/test/phpmailer/)
//FILTER_FLAG_QUERY_REQUIRED – 要求 URL 存在查询字符串(比如:http://levi.cg.am/?p=2618)

10.call_user_fun

official document : https://www.php.net/manual/zh/function.call-user-func.php

简单的
$data = call_user_func(function ($city) {
            return "different " . $city;
        }, "shanghai");

11.get_called_class(获取静态方法调用的类名)


兰亭
3 声望0 粉丝

认识的人越多,我就越喜欢狗


下一篇 »
函数