Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii - How to get a values array from an Active Record

Using Yii, how can I get an array from an Active Record.

Say something like this:

array('foo', 'bar', 'lala')

From something like this:

MyTable::model()->findall()
like image 905
Marian Avatar asked Feb 21 '12 11:02

Marian


2 Answers

If i understand you correctly:

$users = User::model()->findAll();
$usersArr = CHtml::listData( $users, 'id' , 'name');
print_r( $usersArr );

It will give you array id => name

Array {
    2 => 'someone',
    20 => 'kitty',
    102 => 'Marian',
    // ...
}
like image 142
briiC Avatar answered Oct 12 '22 01:10

briiC


For yii2 , use:

yii\helpers\ArrayHelper::map(MyModel::find()->all(), 'id', 'name'));

or

yii\helpers\ArrayHelper::getColumn(MyModel::find()->all(), 'name'));
like image 40
валерий зубков Avatar answered Oct 12 '22 01:10

валерий зубков