S
S
slip312014-06-01 20:11:00
Yii
slip31, 2014-06-01 20:11:00

Yii arrayhelper how to return an array?

There is a method in the model

public static function getItemList($cat_id)
    {
   $models = NetItem::find()->where(['count_id' => $cat_id])->asArray()->all();
   return ArrayHelper::map($models, 'id', 'name_en');
   }

Through the controller, I get
output: {244:Itemname, 245:Itemname2}
A to pass to the widget, I need to make json like this:
$out = [
    ['id'=>244, 'name'=>'Itemname'],
    ['id'=>245, 'name'=>'Itemname2'],
   // and so on
];

How to do it in the simplest way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-06-01
@slip31

public static function getItemList($cat_id)
{

   return array_map(function (array $item) {
        return [
            'id' => $item['id'],
            'name' => $item['name_en'];
        ];
   }, NetItem::find()->where(['count_id' => $cat_id])->asArray()->all());
}

And even better (but I'm not responsible for performance, I don't know how it is in Yii2), specify it explicitly in the select.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question