4
$data = User::find()
    ->select('id, name')
    ->where(['status' => 'active'])
    ->orderBy('id DESC')
    ->asArray()
    ->all();
[
 [0]=>[
        id=>1
        name="test"
      ]
[1]=>[
        id=>2
        name="test1"
      ]
]

What I want is array which looks similar to this. Mapping the id with name so it can be accessed and checked.

[
[1]=>'test'
[2]=>'test1'
]

2 Answers 2

9

Instead of using the ArrayHelper you can directly achieve the desired output by using indexBy() and column() within your query:

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

indexBy() defines the array key, while column() will take the first column in the select condition as value.

Sign up to request clarification or add additional context in comments.

4 Comments

This does not work for numerical fields, such as id being a INTEGER. For indexing by text fields, such as a key field, this does work as expected. When numerical fields are used, the resulting array will be re-indexed, starting with 0. The ArrayHelper solution as proposed by @Vivek does work in both situations.
What does your example look like? I don't think this is true, i just made a little test. Id is an integer value and title a string: Example::find()->select(['title', 'id'])->indexBy('id')->column() works perfect. array(2) { [33]=> string(8) "title1" [47]=> string(9) "title2" }
A hint: need to set "id" as second param in select() as in the example above ->select(['name', 'id']). At first I use vice versa and it not working array returned as ["id" => "id"]
@Lysak the former selected column will be used as value for column(). If you need id => id, then don't even select another column. yiiframework.com/doc/api/2.0/yii-db-query#column()-detail
4

Try this Add the below namespace and use the arrayhelper of Yii2 to map

use yii\helpers\ArrayHelper

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

Comments

Your Answer

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