Bhavuk Suthar
Bhavuk Suthar

Reputation: 101

How to create name value pair array in yii2

i am trying to create an Array in yii2 in following format

[
  ['id'=>'2', 'name'=>'ABC'],
  ['id'=>'3', 'name'=>'DEF']
]

So far i have tried to use ArrayHelper class but if i map using it than it removes the key part from the array,i need to create the array in exact this format

$data = User::find()
        ->where(['id' => $id])
        ->orderBy('id DESC')
        ->all();

As you know after this code i get the data in ActiveRecord format so i need to convert them to id and name array only,i dont need any other data.

I tried doing this

 $data2 = ArrayHelper::map($data, 'id', 'name');

But returns the data in following format

[
  ['2'=>'ABC'],
  ['3'=>'DEF']
]

I have tried this as well

$data = MainCategory::find()->select('id,name')
 ->where(['id' => $id])
  ->orderBy('id DESC') 
 ->asArray()->all();

But its returning the array in following format

[
  '0' =>
      [
       'id'=>'2', 
       'name'=>'ABC'
      ],
  '1' =>
      [
       'id'=>'3', 
       'name'=>'DEF'
      ]
]

How can i achive key and value format in yii2?

Upvotes: 1

Views: 934

Answers (2)

lubosdz
lubosdz

Reputation: 4500

To create plain KEY => VALUE array use column() method:

$data = User::find()
    ->select(['name', 'id'])
    ->where(['id' => $id])
    ->orderBy('id DESC')
    ->asArray()
    ->indexBy('id')
    ->column();

First selected column [name] will be returned as a VALUE.

Upvotes: 0

Double H
Double H

Reputation: 4160

You can fetch data as array like this:

$data = User::find()
    ->select('id, name')
    ->where(['id' => $id])
    ->orderBy('id DESC')
    ->asArray()
    ->all();

Upvotes: 2

Related Questions