S
S
Sergey Beloventsev2018-04-28 20:46:39
Yii
Sergey Beloventsev, 2018-04-28 20:46:39

How to merge arrays with ArrayHelper?

Actually the question in the following is the User model with the properties id, firstName, lastName. Through ArrayHelper I need to combine these fields, that is, something like that.

ArrayHelper::map(User::find()->asArray()->all(),'id','firstName lastName');

The only question is how to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2018-04-28
@slo_nik

are there any other suggestions?

Read the documentation, first I said to myself and now I repeat it to you))))
$form->field($model, 'test')->dropDownList(ArrayHelper::map(User::find()->asArray()->all(), 'id', function($models){
       return $models['firstName'] . ' - ' . $models['lastName'];
   }
 )
)

M
Maxim Timofeev, 2018-05-01
@webinar

Many options, the first one showed @slo_nik
The second one is the toArray method:
https://www.yiiframework.com/doc/guide/2.0/en/help...

$data = ArrayHelper::toArray(User::find()->all(), [
    'app\models\User' => [
        'id',
        'names' => function ($model) {
            return $model->firstName . ' ' . $model->lastName;
        },
    ],
]);
ArrayHelper::map($data, 'id', 'names');

But it's better to create a getter in the User model.
public function getFullName(){
     return $this->firstName . ' ' . $this->lastName;
}

and then:
ArrayHelper::map(User::find()->all(), 'id', 'fullName');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question