yii\helpers\ArrayHelper 是一个数组辅助类,提供额外的数组功能函数

  • toArray($object, $properties = [], $recursive = true)

Converts an object or an array of objects into an array (把对象、数组、字符串安装条件重新转换成数组)

源代码中的例子:

 $properties =
[
'app\models\Post' => [
'id',
'title',
// the key name in array result => property name
'createTime' => 'created_at',
// the key name in array result => anonymous function
'length' => function ($post) {
return strlen($post->content);
},
],
]
$result = ArrayHelper::toArray($post, $properties) ;
//The result of `ArrayHelper::toArray($post, $properties)` could be like the following (结果如下):
* ```php
* [
* 'id' => 123,
* 'title' => 'test',
* 'createTime' => '2013-01-01 12:00AM',
* 'length' => 301,
* ]
* ```
*/
  • merge($a, $b)数组合并 ,支持无限个参数数组合并
   public static function merge($a, $b)
{
$args = func_get_args();
$res = array_shift($args);
while (!empty($args)) {
$next = array_shift($args);
foreach ($next as $k => $v) {
if ($v instanceof UnsetArrayValue) {
unset($res[$k]);
} elseif ($v instanceof ReplaceArrayValue) {
$res[$k] = $v->value;
} elseif (is_int($k)) {
if (isset($res[$k])) {
$res[] = $v;
} else {
$res[$k] = $v;
}
} elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
$res[$k] = self::merge($res[$k], $v);
} else {
$res[$k] = $v;
}
}
} return $res;
}

其中if ($v instanceof UnsetArrayValue) { unset($res[$k])};

UnsetArrayValue   yii\helpers\UnsetArrayValue  类注释可以看出具体作用

/**
* Object that represents the removal of array value while performing [[ArrayHelper::merge()]].
*
* Usage example:
*
* ```php
* $array1 = [
* 'ids' => [
* 1,
* ],
* 'validDomains' => [
* 'example.com',
* 'www.example.com',
* ],
* ];
*
* $array2 = [
* 'ids' => [
* 2,
* ],
* 'validDomains' => new \yii\helpers\UnsetArrayValue(),
* ];
*
* $result = \yii\helpers\ArrayHelper::merge($array1, $array2);
* ```
*
* The result will be
*
* ```php
* [
* 'ids' => [
* 1,
* 2,
* ],
* ]
* ```
*
* @author Robert Korulczyk <robert@korulczyk.pl>
* @since 2.0.10
*/

其中elseif ($v instanceof ReplaceArrayValue) { $res[$k] = $v->value};

UnsetArrayValue   yii\helpers\ReplaceArrayValue类注释可以看出具体作用

 /**
* Object that represents the replacement of array value while performing [[ArrayHelper::merge()]].
*
* Usage example:
*
* ```php
* $array1 = [
* 'ids' => [
* 1,
* ],
* 'validDomains' => [
* 'example.com',
* 'www.example.com',
* ],
* ];
*
* $array2 = [
* 'ids' => [
* 2,
* ],
* 'validDomains' => new \yii\helpers\ReplaceArrayValue([
* 'yiiframework.com',
* 'www.yiiframework.com',
* ]),
* ];
*
* $result = \yii\helpers\ArrayHelper::merge($array1, $array2);
* ```
*
* The result will be
*
* ```php
* [
* 'ids' => [
* 1,
* 2,
* ],
* 'validDomains' => [
* 'yiiframework.com',
* 'www.yiiframework.com',
* ],
* ]
* ```
*
* @author Robert Korulczyk <robert@korulczyk.pl>
* @since 2.0.10
*/

getValue($array, $key, $default = null)  根据数组的键获取数组元素的值或者根据对象的属性名称或者对象的属性值

 /**
* ```php
* // working with array 数组
* $username = \yii\helpers\ArrayHelper::getValue($_POST, 'username');
* // working with object 对象
* $username = \yii\helpers\ArrayHelper::getValue($user, 'username');
* // working with anonymous function 匿名函数
* $fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) {
* return $user->firstName . ' ' . $user->lastName;
* });
* // using dot format to retrieve(得到) the property of embedded(嵌入、内嵌式) object
* $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
* // using an array of keys to retrieve the value
* $value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
* ```
*/
  • remove(&$array, $key, $default = null) 删除数组指定键值
  • getColumn($array, $name, $keepKeys = true) 在一个数组中获取指定列的值,由指定列的值组成新的数组返回  参数$keepKeys返回数组是否保持第一层的key
 /**
* Returns the values of a specified column in an array.
* The input array should be multidimensional(多维的) or an array of objects.
*
* For example,
*
* ```php
* $array = [
* ['id' => '123', 'data' => 'abc'],
* ['id' => '345', 'data' => 'def'],
* ];
* $result = ArrayHelper::getColumn($array, 'id');
* // the result is: ['123', '345']
*
* // using anonymous function
* $result = ArrayHelper::getColumn($array, function ($element) {
* return $element['id'];
* });
* ```
*
* @param array $array
* @param string|\Closure $name
* @param boolean $keepKeys whether to maintain(维持、保持) the array keys. If false, the resulting array
* will be re-indexed with integers.
* @return array the list of column values
*/

map($array, $from, $to, $group = null) 从一个多维数组或者对象中建立一个键值对的映射组成新的数组返回

 /**
* Builds a map (key-value pairs) from a multidimensional(多维的) array or an array of objects.
* The `$from` and `$to` parameters specify the key names or property names to set up(建立) the map(映射、地图).
* Optionally, one can further group the map according to a grouping field `$group`.
*
* For example,
*
* ```php
* $array = [
* ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
* ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
* ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
* ];
*
* $result = ArrayHelper::map($array, 'id', 'name');
* // the result is:
* // [
* // '123' => 'aaa',
* // '124' => 'bbb',
* // '345' => 'ccc',
* // ]
*
* $result = ArrayHelper::map($array, 'id', 'name', 'class');
* // the result is:
* // [
* // 'x' => [
* // '123' => 'aaa',
* // '124' => 'bbb',
* // ],
* // 'y' => [
* // '345' => 'ccc',
* // ],
* // ]
* ```
*
* @param array $array
* @param string|\Closure $from
* @param string|\Closure $to
* @param string|\Closure $group
* @return array
*/
  • keyExists($key, $array, $caseSensitive = true) 检查数组是否存在指定的键 $caseSensitive 参数 是否区分大小写 默认ture区分
  • isIn($needle, $haystack, $strict = false) Check whether an array or [[\Traversable]] contains an element. 检查数组或者 可遍历的元素 (\Traversable )是否包含指定元素  $strict = false 是否严格匹配(值和类型)
  • htmlEncode($data, $valuesOnly = true, $charset = null)     Encodes(编码) special characters(字符) in an array of strings into HTML entities(实体)   编码在数组中的特殊的字符转成html 实体 $valuesOnly = true (是否只是值转化为html实体,默认是true)
  • htmlDecode($data, $valuesOnly = true)  Decodes(解码) HTML entities(实体) into the corresponding(相应的) characters(字符) in an array of strings. $valuesOnly = true(是否只有值解码 ,默认是true)
  • multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR) 数组排序

Yii2 yii\helpers\ArrayHelper的更多相关文章

  1. 简单分析下用yii2的yii\helpers\Html类和yii.js实现的post请求

    yii2提供了很多帮助类,比如Html.Url.Json等,可以很方便的实现一些功能,下面简单说下这个Html.用yii2写view时时经常会用到它,今天在改写一个页面时又用到了它.它比较好用的地方就 ...

  2. yii2 ./yii command : No such file or directory

    git clone下来的yii2后台项目,由于需要执行 ./yii migrate命令.执行之后,提示 No such file or directory 我从同样为yii2 basic的./yii ...

  3. yii2 ArrayHelper map 使用

    <不喜勿喷> 引用类 use yii\helpers\ArrayHelper; 源码中修改(尽量不要修改,可以研究下不修改的方式) 源码路径 查看数据 视图层 实现效果

  4. Yii2 脚本手动执行可以,计划任务执行不成功

    用Yii2的console写了个脚本,在命令行执行都OK. 放到cron里面也按时去执行了,但就是执行的效果不对,console脚本执行结果不对. 查看之后的是由于yii脚本的php路径问题(跟目录下 ...

  5. 改写yii2的listview功能

    在vendor\yiisoft\yii2\widgets路径下新增文件ListViewtest,将下列代码粘贴并保存 <?php namespace yii\widgets; use Yii;u ...

  6. yii 核心类classes.php详解(持续更新中...)

    classes.php在yii运行的时候将被自动加载,位于yii2文件夹底下. <?php /** * Yii core class map. * * This file is automati ...

  7. Yii应用的目录结构和入口脚本

    以下是一个通过高级模版安装后典型的Yii应用的目录结构: . ├── backend ├── common ├── console ├── environments ├── frontend ├── ...

  8. Yii2安装搭建和将入口文件移到根目录

    用Composer下载Yii2速度太慢了,所以我还是喜欢下载打包好的框架文件. 在https://github.com/yiisoft/yii2/releases 下载最新的的Yii2,advance ...

  9. PHP在yii2中封装SuperSlide 幻灯片编写自己的SuperSlideWidget的例子

    因为近期给朋友公司做个门户网站,把荒置了6.7年的PHP又重新拾起,发现PHP这些年兴旺多了,很多新的东西看的不明不白,研究了几个框架ZendFramework.thinkphp.Symfony.yi ...

随机推荐

  1. [iOS]UIInterpolatingMotionEffect重力视觉差

    - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typica ...

  2. SessionStroage和locationStorage的思考

    从理论上讲 LocalStroage 内存更大,存储时间更为持久,作用域更大.那么SessionStroage有存在的必要吗?有什么样的应该场景是必须用seessionStroage 而不能使用Loc ...

  3. 【python 虚拟环境 virtualenv的配置】

    该目录内生成一个虚目录: #运行activcate下的shell脚本,激活虚拟环境 #pip  python包管理器

  4. hive在客户机启动时出现的问题

    运行环境:一拖一分布式集群+客户端 mysql和hive安装在客户机上 问题:在客户机终端启动hive时出现如下问题: 目前还没有找出是什么原因! 解决办法: 参照http://dblab.xmu.e ...

  5. 网站漏洞修复案例之Discuz!3.4最新版本

    Discuz!论坛目前最新版本为3.4版本,已经好久没有更新了,我们SINE安全在对其网站安全检测的同时发现一处漏洞,该漏洞可导致论坛的后台文件可以任意的删除,导致网站瘫痪,后台无法登陆.关于该网站漏 ...

  6. Leecode刷题之旅-C语言/python-231 2的幂

    /* * @lc app=leetcode.cn id=231 lang=c * * [231] 2的幂 * * https://leetcode-cn.com/problems/power-of-t ...

  7. 双端队列 ADT接口 数组实现

    Deque ADT接口 DEQUEUE.h: #include <stdlib.h> #include "Item.h" void DEQUEUEinit(int); ...

  8. 原生js三级联动

    <!DOCTYPE html> <html lang="en"> <head> <title> 三级联动 </title> ...

  9. R语言学习笔记—组合数

    组合数:从m个不同元素中取出n(n≤m)个元素的所有组合的个数,叫做从m个不同元素中取出n个元素的组合数. 代码: str_comb <- function(vector){ n <- l ...

  10. leetcode-744-Find Smallest Letter Greater Than Target(改进的二分查找)

    题目描述: Given a list of sorted characters letters containing only lowercase letters, and given a targe ...