php - Extracting data from array in Yii 2

770

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 ?

38

Answer

Solution:

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()),
    ],
]);
472

Answer

Solution:

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

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:

People are also looking for solutions to the problem: codeigniter - PHP Sort Order Process Codeiginiter

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.