Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting key value pair array in Yii2

Tags:

yii2

$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

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.

like image 54
nadar Avatar answered Sep 20 '25 22:09

nadar


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

use yii\helpers\ArrayHelper

$userdata = ArrayHelper::map($data, 'id', 'name');
like image 32
Vivek Avatar answered Sep 20 '25 20:09

Vivek