1

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?

2
  • Returning array is the same as you mentioned in the very beginning. What's the current problem? Commented Nov 2, 2015 at 3:20
  • @arogachev when i fire the query it returns the array in the last format i posted in question but i want to achieve the format which is on top,without grouping Commented Nov 2, 2015 at 3:41

2 Answers 2

2

You can fetch data as array like this:

$data = User::find()
    ->select('id, name')
    ->where(['id' => $id])
    ->orderBy('id DESC')
    ->asArray()
    ->all();
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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.