|
- <?php
- /**
- * Created by PhpStorm.
- * User: wangxj
- * Date: 2017/5/27
- * Time: 18:10
- */
-
- namespace common\components;
-
-
- use yii\helpers\ArrayHelper;
-
- class zComponents
- {
- /**
- * User: wangxj
- *
- * 和ArrayHelper::map区别
- * 供dropDownList在<option >添加额外属性<option data-type='type1' >
- * $result = ArrayHelper::map($array, 'type', 'name', 'id')
- *
- * $array = [
- * ['id' => '123', 'name' => 'aaa', 'class' => 'x', 'type' => 'type1'],
- * ['id' => '124', 'name' => 'bbb', 'class' => 'x', 'type' => 'type1'],
- * ['id' => '345', 'name' => 'ccc', 'class' => 'y', 'type' => 'type2'],
- * ];
- *
- * // the result is:
- * // [
- * // '123' => [
- * // 'type' => 'type1',
- * // ],
- * // '124' => [
- * // 'type' => 'type1',
- * // ],
- * // '345' => [
- * // 'type' => 'type2',
- * // ],
- * // ]
- *
- * @param $array
- * @param $from
- * @param $to
- * @param null $group
- * @return array
- */
- public static function map($array, $from, $to, $group = null)
- {
- $result = [];
- foreach ($array as $element) {
- $key = ArrayHelper::getValue($element, $from);
- $value = ArrayHelper::getValue($element, $to);
- if ($group !== null) {
- $result[ArrayHelper::getValue($element, $group)][$key] = $value;
- } else {
- $result[$key] = $value;
- }
- }
-
- return $result;
- }
- }
|