简体   繁体   中英

Yii Php: Getting values having a specific key in an associative array

I have a model/database table that looks like this

id | group_id| first_name | middle_name | last_name
------------------------------------------------------ 
   |          |            |             |      
------------------------------------------------------

After retrieving a model from the database:

say:

$people = PersonModel::model()->findAllByAttributes(array('group_id'=>$groupId));

and suppose i've retrieved 10 rows.. matching the groupId given

I want to store all the first_name of the 10 rows that matched.

I know this can be done by:

$personArray = array();
foreach($people as $person){
   $personArray[] = $person->first_name;
}

but is there another way, eg a php function that does the same thing? Thank you!

$criteria = new CDbCriteria;
$criteria->compare('group_id', $groupId);
$criteria->limit = 10;
$people = PersonModel::model()->findAll($criteria);
$personArray = $list = CHtml::listData($people, 'id','first_name');

The CHtml::listData() returns an associative array with like: ['id'] => 'first_name' (attributes of the model)

you can first count the models matching your group_id, like:

PersonModel::model()->countByAttributes(array('group_id'=>$groupId));

then you can limit it to 10 and order it desc and get the latest 10 rows that matched!

Yii : how to count records in a model?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM