yii\helpers\BaseArrayHelper::map PHP Метод

map() публичный статический Метод

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', ], ]
public static map ( array $array, string | Closure $from, string | Closure $to, string | Closure $group = null ) : array
$array array
$from string | Closure
$to string | Closure
$group string | Closure
Результат 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;
    }

Usage Example

Пример #1
0
 public static function getList()
 {
     $data = self::find()->all();
     if ($data === null) {
         throw new HttpException(404, "Ошибка");
     }
     return \yii\helpers\BaseArrayHelper::map($data, 'id', 'name');
 }
All Usage Examples Of yii\helpers\BaseArrayHelper::map