php Yii2.0 ArrayHelper::map() 用法剖析
2016-12-27 10:15
591 查看
从多维数组或数组中构建一个映射(键-值 的形式)
通过“
当然也可以根据分组字段“
举个例子:
上面的数组执行以下方法
得到的结果是
还可以添加第四个参数
得到的结果是
下面是map方法的详细代码
文章转载自 http://u.cxyblog.com/10/article-aid-329.html
通过“
$from”和“
$to”参数指定对应的键值或属性名称来设置的映射关系。
当然也可以根据分组字段“
$group”来进一步分组的映射。
举个例子:
$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');
得到的结果是
[ '123' => 'aaa', '124' => 'bbb', '345' => 'ccc', ]
还可以添加第四个参数
$result = ArrayHelper::map($array, 'id', 'name', 'class');
得到的结果是
[ 'x' => [ '123' => 'aaa', '124' => 'bbb', ], 'y' => [ '345' => 'ccc', ], ]
下面是map方法的详细代码
/** * @paramarray $array * @param string|Closure $from * @param string|Closure $to * @param string|Closure $group * @return array */ public static function map($array, $from, $to, $group = null) { $result = []; foreach ($array as $element) { $key = static:: getValue($element, $from); $value = static:: getValue($element, $to); if ($group !== null) { $result[ static:: getValue($element, $group)][$key] = $value; } else { $result[$key] = $value; } } return $result; }
文章转载自 http://u.cxyblog.com/10/article-aid-329.html
相关文章推荐
- php中array_reduce和array_map的用法
- PHP中array_map用法
- [Yii2小心肝儿]ArrayHelper之map详解(你不太用的第三个参数)
- PHP中array_map与array_column之间的关系分析
- PHP排序函数array_multisort用法【…
- (转载)php之call_user_func_array的简易用法
- ARRAY_MAP函数用法
- PHP 函数 array_map() 和 call_user_func_array() 的妙用
- PHP数组排序 array_multisort函数详细用法跟排序方法
- PHP 函数 array_map 使用心得
- PHP 函数 array_map() 和 call_user_func_array() 的妙用
- php 自己写的一个数组分类合并array_merge(函数的剖析)
- PHP中array_map的妙用
- PHP中array_chunk的用法
- php学习之道:call_user_func和call_user_func_array的用法
- PHP 函数call_user_func和call_user_func_array用法详解
- php-Arrays 函数-array_map-将回调函数作用到给定数组的单元上
- PHP中array_map的使用
- PHP复合数据类型array的用法解析
- 【php】php中call_user_func_array和call_user_func函数的用法