2

I'm trying to get data from DB and show it in menu.

echo NavX::widget([
    'options' => ['class' => 'navbar-nav navbar-right'],
    'items' => [
        array_map(function ($model) {
            return [
                'label' => $model['param2'],
                'url' => ["/users/{$model['param3']}"],
            ];
        }, Model::find()->where(['userID' => 32])->asArray()->all()),
    ],
]);

But unfortunately this code is wrong, error says:

Array to string conversion

Is there any other way to fix it ?

4
  • You try to echo an array there. Put a foreach around it and echo the items in the array. Commented Apr 20, 2015 at 6:12
  • I cannot because I user this code while building menu tree in yii2. There is NavX::widget([ with it's 'options, items etc... Commented Apr 20, 2015 at 6:16
  • Then plz show more code, that surrounds it. Commented Apr 20, 2015 at 6:17
  • Check main post again please Commented Apr 20, 2015 at 6:19

2 Answers 2

1

My guess, without testing:

echo NavX::widget([
    'options' => ['class' => 'navbar-nav navbar-right'],
    'items' => [
        array_map(function ($model) {
            return [
                'label' => $model['param2'],
                'url' => "/users/{$model['param3']}", // <--- string, not array!
            ];
        }, Model::find()->where(['userID' => 32])->asArray()->all()),
    ],
]);
Sign up to request clarification or add additional context in comments.

Comments

0

One of the "Yii" way to do it will be using built-in ArrayHelper:

use yii\helpers\ArrayHelper;

...

$models = Model::find()->where(['userID' => 32])->asArray()->all();
$items = ArrayHelper::toArray($models, [
    'app\models\Model' => [    
        'label' => function ($model) {
            // Add label generation code here
        },
        'url' => function ($model) {
            // Add url generation code here
        }
    ],
]);

Then just pass the $items to your view with menu.

Official docs:

3 Comments

Show your code, especially how you are building label and url.
in label generation code I use - return $model['param2']; But after all this code when I echo $items I get - Array to string conversion
Try without asArray().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.