Yii 2 get IDs into an array

Hi,

I want to do a findAll and get all of the IDs into an array.

What is the best way to do this, I notice Yii 2 has an asArray() method and a toArray() method, is it possible to do it using these? If so, can you show me how?

I know how to do it via findAll records manually and then running a foreach loop etc and creating a new array from it but I am not looking for that.

I am looking for the best way to do it.

Any ideas?

James.

Hi!

I think ArrayHelper::map is what you are looking for.

there are a lot of nice array helpers take a look at this:

http://www.yiiframework.com/doc-2.0/guide-helper-array.html

Example:




use yii\helpers\ArrayHelper; 

// ...


// in your model function: 

$query = static::find()->orderBy('attribute_1 ASC')->all();

return ArrayHelper::map($query, 'attribute_1', 'attribute_2');


/* 

you should receive an array like: 

array(

	'attribute_1_value_1' 	=> 'attribute_2_value_1',

	'attribute_1_value_2' 	=> 'attribute_2_value_2',

	'attribute_1_value_3' 	=> 'attribute_2_value_3',

)

*/




Hope this helps.

Regards

Ok thanks.

There’s also a method in ActiveQuery for directly achieving this:

$ids = User::find()->select('id')->column();
1 Like