Yii2.0 ArrayHelper::map() 使用方法
2016-07-07 00:00
671 查看
![](https://oscdn.geek-share.com/Uploads/Images/Content/201607/8043a463193171dfa8f79c63d8e44b08.png)
从多维数组或数组中构建一个映射(键-值 的形式)
通过“$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', '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;
}
相关文章推荐
- Yii2.0数据库操作增删改查详解
- yii2.0 widget小部件制作教程
- yii2.0 UrlManage链接url规则解析
- yii2.0分页的基本使用及其配置详解
- 日请求亿级的QQ会员AMS平台PHP7升级实践
- phpmailer 使用
- 使用mutt和msmtp发送邮件
- ThinkPHP,连贯操作between
- PHP Date使用
- PHP 开发者该知道的 5 个 Composer 小技巧
- [转]ftp到底是什么?它是干什么的
- 激活phpstorm的链接
- PHP安装
- PHP并发IO编程之路
- mod_php对比mod_fastcgi
- Php 命名空间
- PHP 精确验证身份证号
- PHP 身份证号码验证代码
- ubuntu php5.3升级到5.4
- PagerAdapter和FragmentPagerAdapter和FragmentStatePagerAdapter区别