当前位置: 首页 > news >正文

30秒的PHP代码片段(1)数组 - Array

本文来自GitHub开源项目

点我跳转

30秒的PHP代码片段

clipboard.png

精选的有用PHP片段集合,您可以在30秒或更短的时间内理解这些片段。

排列

all

如果所提供的函数返回 true 的数量等于数组中成员数量的总和,则函数返回 true,否则返回 false

function all($items, $func)
{
    return count(array_filter($items, $func)) === count($items);
}

Examples

all([2, 3, 4, 5], function ($item) {
    return $item > 1;
}); // true

any

如果提供的函数对数组中的至少一个元素返回true,则返回true,否则返回false

function any($items, $func)
{
    return count(array_filter($items, $func)) > 0;
}

Examples

any([1, 2, 3, 4], function ($item) {
    return $item < 2;
}); // true

deepFlatten(深度平铺数组)

将多维数组转为一维数组

function deepFlatten($items)
{
    $result = [];
    foreach ($items as $item) {
        if (!is_array($item)) {
            $result[] = $item;
        } else {
            $result = array_merge($result, deepFlatten($item));
        }
    }

    return $result;
}

Examples

deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]

drop

返回一个新数组,并从左侧弹出n个元素。

function drop($items, $n = 1)
{
    return array_slice($items, $n);
}

Examples

drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]

findLast

返回所提供的函数为其返回的有效值(即过滤后的值)的最后一个元素的键值(value)。

function findLast($items, $func)
{
    $filteredItems = array_filter($items, $func);

    return array_pop($filteredItems);
}

Examples

findLast([1, 2, 3, 4], function ($n) {
    return ($n % 2) === 1;
});
// 3

findLastIndex

返回所提供的函数为其返回的有效值(即过滤后的值)的最后一个元素的键名(key)。

function findLastIndex($items, $func)
{
    $keys = array_keys(array_filter($items, $func));

    return array_pop($keys);
}

Examples

findLastIndex([1, 2, 3, 4], function ($n) {
    return ($n % 2) === 1;
});
// 2

flatten(平铺数组)

将数组降为一维数组

function flatten($items)
{
    $result = [];
    foreach ($items as $item) {
        if (!is_array($item)) {
            $result[] = $item;
        } else {
            $result = array_merge($result, array_values($item));
        }
    }

    return $result;
}

Examples

flatten([1, [2], 3, 4]); // [1, 2, 3, 4]

groupBy

根据给定的函数对数组的元素进行分组。

function groupBy($items, $func)
{
    $group = [];
    foreach ($items as $item) {
        if ((!is_string($func) && is_callable($func)) || function_exists($func)) {
            $key = call_user_func($func, $item);
            $group[$key][] = $item;
        } elseif (is_object($item)) {
            $group[$item->{$func}][] = $item;
        } elseif (isset($item[$func])) {
            $group[$item[$func]][] = $item;
        }
    }

    return $group;
}

Examples

groupBy(['one', 'two', 'three'], 'strlen'); // [3 => ['one', 'two'], 5 => ['three']]

hasDuplicates(查重)

检查数组中的重复值。如果存在重复值,则返回true;如果所有值都是唯一的,则返回false

function hasDuplicates($items)
{
    return count($items) > count(array_unique($items));
}

Examples

hasDuplicates([1, 2, 3, 4, 5, 5]); // true

head

返回数组中的第一个元素。

function head($items)
{
    return reset($items);
}

Examples

head([1, 2, 3]); // 1

last

返回数组中的最后一个元素。

function last($items)
{
    return end($items);
}

Examples

last([1, 2, 3]); // 3

pluck

检索给定键名的所有键值

function pluck($items, $key)
{
    return array_map( function($item) use ($key) {
        return is_object($item) ? $item->$key : $item[$key];
    }, $items);
}

Examples

pluck([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
], 'name');
// ['Desk', 'Chair']

pull

修改原始数组以过滤掉指定的值。

function pull(&$items, ...$params)
{
    $items = array_values(array_diff($items, $params));
    return $items;
}

Examples

$items = ['a', 'b', 'c', 'a', 'b', 'c'];
pull($items, 'a', 'c'); // $items will be ['b', 'b']

reject

使用给定的回调筛选数组。

function reject($items, $func)
{
    return array_values(array_diff($items, array_filter($items, $func)));
}

Examples

reject(['Apple', 'Pear', 'Kiwi', 'Banana'], function ($item) {
    return strlen($item) > 4;
}); // ['Pear', 'Kiwi']

remove

从给定函数返回false的数组中删除元素。

function remove($items, $func)
{
    $filtered = array_filter($items, $func);

    return array_diff_key($items, $filtered);
}

Examples

remove([1, 2, 3, 4], function ($n) {
    return ($n % 2) === 0;
});
// [0 => 1, 2 => 3]

tail

返回数组中的所有元素,第一个元素除外。

function tail($items)
{
    return count($items) > 1 ? array_slice($items, 1) : $items;
}

Examples

tail([1, 2, 3]); // [2, 3]

take

返回一个数组,其中从开头删除了n个元素。

function take($items, $n = 1)
{
    return array_slice($items, 0, $n);
}

Examples

take([1, 2, 3], 5); // [1, 2, 3]
take([1, 2, 3, 4, 5], 2); // [1, 2]

without

筛选出给定值之外的数组元素。

function without($items, ...$params)
{
    return array_values(array_diff($items, $params));
}

Examples

without([2, 1, 2, 3, 5, 8], 1, 2, 8); // [3, 5]

orderBy

按键名对数组或对象的集合进行排序。

function orderBy($items, $attr, $order)
{
    $sortedItems = [];
    foreach ($items as $item) {
        $key = is_object($item) ? $item->{$attr} : $item[$attr];
        $sortedItems[$key] = $item;
    }
    if ($order === 'desc') {
        krsort($sortedItems);
    } else {
        ksort($sortedItems);
    }

    return array_values($sortedItems);
}

Examples

orderBy(
    [
        ['id' => 2, 'name' => 'Joy'],
        ['id' => 3, 'name' => 'Khaja'],
        ['id' => 1, 'name' => 'Raja']
    ],
    'id',
    'desc'
); // [['id' => 3, 'name' => 'Khaja'], ['id' => 2, 'name' => 'Joy'], ['id' => 1, 'name' => 'Raja']]

相关文章:
30秒的PHP代码片段(2)数学 - Math
30秒的PHP代码片段(3)字符串-String & 函数-Function

相关文章:

  • docker-2-安装
  • 使用 QuickBI 搭建酷炫可视化分析
  • 使用rsyslog收集日志
  • 日剧·日综资源集合(建议收藏)
  • 码农张的Bug人生 - 见面之礼
  • Java求两个数平均值
  • 01炼数成金TensorFlow基本概念
  • Spark调度模块
  • 封装dialog弹窗
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • CentOS6 Shell脚本/bin/bash^M: bad interpreter错误解决方法
  • 搭建gitbook 和 访问权限认证
  • 测试开发系类之接口自动化测试
  • Chrome 控制台报错Unchecked runtime.lastError: The message port closed before a response was received...
  • 读vue源码看前端百态2--打包工具
  • JavaScript-如何实现克隆(clone)函数
  • 2017届校招提前批面试回顾
  • Android 控件背景颜色处理
  • docker容器内的网络抓包
  • Gradle 5.0 正式版发布
  • HashMap剖析之内部结构
  • laravel 用artisan创建自己的模板
  • PHP那些事儿
  • Three.js 再探 - 写一个跳一跳极简版游戏
  • ViewService——一种保证客户端与服务端同步的方法
  • webpack入门学习手记(二)
  • 案例分享〡三拾众筹持续交付开发流程支撑创新业务
  • 搭建gitbook 和 访问权限认证
  • 反思总结然后整装待发
  • 基于 Babel 的 npm 包最小化设置
  • 基于webpack 的 vue 多页架构
  • 每个JavaScript开发人员应阅读的书【1】 - JavaScript: The Good Parts
  • 前端工程化(Gulp、Webpack)-webpack
  • 适配mpvue平台的的微信小程序日历组件mpvue-calendar
  • 中文输入法与React文本输入框的问题与解决方案
  • 阿里云ACE认证学习知识点梳理
  • ###C语言程序设计-----C语言学习(6)#
  • $(document).ready(function(){}), $().ready(function(){})和$(function(){})三者区别
  • (2022 CVPR) Unbiased Teacher v2
  • (cljs/run-at (JSVM. :browser) 搭建刚好可用的开发环境!)
  • (读书笔记)Javascript高级程序设计---ECMAScript基础
  • (非本人原创)史记·柴静列传(r4笔记第65天)
  • (官网安装) 基于CentOS 7安装MangoDB和MangoDB Shell
  • (离散数学)逻辑连接词
  • (三分钟)速览传统边缘检测算子
  • (深入.Net平台的软件系统分层开发).第一章.上机练习.20170424
  • (转)memcache、redis缓存
  • *p=a是把a的值赋给p,p=a是把a的地址赋给p。
  • *上位机的定义
  • .【机器学习】隐马尔可夫模型(Hidden Markov Model,HMM)
  • .NET 4.0网络开发入门之旅-- 我在“网” 中央(下)
  • .NET Core中的去虚
  • .Net IE10 _doPostBack 未定义
  • .net MySql
  • .NET NPOI导出Excel详解