Yii2-助手类(ArrayHelper)
数组助手类 ArrayHelper
Yii 数组助手类提供了额外的静态方法,让你更高效的处理数组。
模型转数组
$model = Country::findOne(['code'=>'BR']);
VarDumper::dump(ArrayHelper::toArray($model)); //[ 'code' => 'BR' 'name' => 'Brazil' 'population' => 170115000 ]
获取值(getValue)
class User
{
public $name = 'Alex';
}
$array = [
'foo' => [
'bar' => new User(),ddd
]
]
获取 name 的值
PHP 方法:
$value = isset($array['foo']['bar']->name) ? $array['foo']['name'] : null;
ArrayHelper 方法:
$value = ArrayHelper::getValue($array,'foo.bar.name');
获取列(getColumn)
从多维数组或者对象数组中获取某列的值
$data = [
['id' => '123','data' => 'abc'], // key 相当于对象的属性名,value 相当于对象的属性值
['id' => '456','data' => 'def'],
]
ArrayHelper 方法:
$ids = ArrayHelper::getColumn($data,'id');
结果:['123','456'];
移除数组指定key的项
$array = ['name'=>'xiaoming','age'=>23];
$r = ArrayHelper::remove($array,'name');
VarDumper::dump($array);
结果:['age'=>23]
移除指定值的项
$array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
\yii\helpers\ArrayHelper::removeValue($array, 'Jackson');
VarDumper::dump($array);
结果:[ 'Bob' => 'Dylan' 'Mick' => 'Jagger' ]
根据指定的键对数组进行索引或分组
$array = [
['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
['id' => '345', 'data' => 'def', 'device' => 'tablet'],
['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
];
//索引
$result = ArrayHelper::index($array, 'id');
VarDumper::dump($result);
//分组
$result = ArrayHelper::index($array, null,'id');
//以id和device分组
$result = ArrayHelper::index($array, 'data', [function ($element) {return $element['id'];}, 'device']);
VarDumper::dump($result);
建立映射表(map)
可以使用 map 方法从一个多维数组或者对象数组中取出数据,建立一个映射表(键值对数组), 在 map 方法的参数列表中指定了预构建的映射表的键名和值。
$array = [
['id'=>'123','name'=>'aaa','email'=>'x'],
['id'=>'456','name'=>'bbb','email'=>'y'],
['id'=>'789','name'=>'ccc','email'=>'z'],
]
// ArrayHelper 方法:
$result = ArrayHelper::map($array,'id','name');
/*
结果:
[
'123' => 'aaa'
'456' => 'bbb'
'789' => 'ccc,
]
*/
转HTML 实体
$array = ['html'=>"<script>console.log('test');</script>"];
$result = ArrayHelper::htmlEncode($array);
根据指定的key筛选数组
$array = [
'A' => [1, 2],
'B' => [
'C' => 1,
'D' => 2,
],
'E' => 1,
];
$result = ArrayHelper::filter($array,['A','B']);
标签:name,ArrayHelper,助手,result,数组,array,Yii2,id
From: https://www.cnblogs.com/hu308830232/p/18105494