C
C
Caspergreen2018-06-25 09:52:43
Yii
Caspergreen, 2018-06-25 09:52:43

Why is the last array element returned in DetailView, yii2?

I take out

[
                'label' => 'User',
                'format' => 'html',
                'value' => function($model) {
                    foreach (UserHelper::getName($model->user_id) as $val) {
                        return $val['name'];
                    }
                }
            ],

Returns the last element in the array.
getName function
public function getName($json) {
        $json = json_decode($json, true);
        $uid = [];
        foreach($json as $id){
            $uid[] = $id['user_id'];
        }
        foreach(User::findAll(['id' => $uid]) as $user){
            $name[] = ['name' => $user['name']]; 
        }
        return $name;
        
    }

$json variable How to display names separated by commas in detailview?
[{"user_id":"1"},{"user_id":"2"}]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-06-25
@Caspergreen

Good morning.
There is such a thing as implode()
And the solution might look like this:

$users = User::find()->select('name')->where(['id' => $uid])->column();
echo implode(',', $users);

This will change your code to:
'value' => function($model) {
    $users = User::find()->select('name')->where(['id' => $uid])->column();
    return implode(',', $users);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question