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. Oracle锁处理、解锁方法

    1.查询锁情况 select sid,serial#,event,BLOCKING_SESSION from v$session where event like '%TX%'; 2.根据SID查询具 ...

  2. Oracle特有函数 case when decode exists 分页rownum

    select * from EMP eselect * from dept dselect * from salgrade s--Oracle特有函数 case whenselect case 2 w ...

  3. [iOS]CIFilter滤镜

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

  4. angular setInterval计时操作

    在angular中setInterval方法是单向绑定,只绑定一次,无法实现计时效果, 可以使用$interval实现.附上代码:

  5. Ubuntu18.04安装mysql及相关配置

    step 1: sudo apt-get update step 2: sudo apt-get install mysql-server step3: 查看mysql服务端是否开启 systemct ...

  6. VUE 采坑之旅-- Mint-ui 按需引入报出Module build failed: Error: Couldn't find preset "es2015" relative to directory "C:\\phpStudy\\PHPTutorial\\WWW\\text\\vuep\\vue-demo"

    首先按照mint-ui的文档中按需引入的要求,先执行 npm install babel-plugin-component -D 然后,将.babelrc文件替换了,但是后来我又将其改了(采坑过程我也 ...

  7. MongoDB可视化工具RoboMongo

    官网下载安装包:https://robomongo.org/download (开始使用的是mongoVUE,研究半天,最后发现貌似已经挂掉了,坑!后来上手的robomongo) 安装没什么说的,一直 ...

  8. 通过SSH服务登陆linux服务器(版本RHEL7)

    通过SSH服务登陆linux服务器(版本RHEL7) SSH服务概述:是一种能够以安全的方式提供远程登陆的协议,也是目前远程管理linux系统的首选方式.在此之前,我们一般使用FTP或者telnet来 ...

  9. ubuntu 设置环境变量

    两种方式设置环境变量: 1,添加到环境变量路径$PATH中 # 加到PATH末尾 export PATH=$PATH:/path/to/your/dir # 加到PATH开头 export PATH= ...

  10. Visual SVN 备份

    -----------2018.11.27更新-------------- 这两天把SVN的服务器重做了,按照之前的LOAD,DUMP的方法备份恢复.发现了以下问题: 1,时间比较长,备份和恢复都很长 ...