Home  >  Article  >  PHP Framework  >  How to use indexBy() in Yii2

How to use indexBy() in Yii2

angryTom
angryTomforward
2019-11-26 16:55:412615browse

How to use indexBy() in Yii2

In project development, some special values ​​are often used as the index of the array. Generally, the data can be queried first and then the array can be spliced ​​into the required format in a loop. However, the YII2 framework provides a simpler method indexBy().

When you call the all() method, it will return an array indexed by consecutive integer values.
Sometimes you may want to use a specific field or expression value as the index result set array. Then you can use the indexBy() method before calling all() to achieve this purpose.
For example,

// 以uid作为key值
$query = User::find()
    ->select(['uid', 'name'])
    ->indexBy('uid')
    ->asArray()
    ->all();

The query results are as follows:

{
  "1001": {
    "uid": "1001",
    "name": "张三"
  },
  "1002": {
    "uid": "1002",
    "name": "李四"
  },
  "1003": {
    "uid": "1003",
    "name": "王五"
  }
}

If you need to use the value of the expression as the index, you only need to pass an anonymous function to the indexBy() method:

// 以uid和name组合作为key值
$query = User::find()
    ->select(['uid', 'name'])
    ->indexBy(function ($row) {
        return $row['uid'] . $row['name'];   // row中使用的字段名只能是查询返回的字段名
    })
    ->asArray()
    ->all();

The query results are as follows:

{
  "1001张三": {
    "uid": "1001",
    "name": "张三"
  },
  "1002李四": {
    "uid": "1002",
    "name": "李四"
  },
  "1003王五": {
    "uid": "1003",
    "name": "王五"
  }
}

Note: Unlike query methods such as groupBy() or orderBy(), they will be converted into part of the SQL query statement, and this method (indexBy) is used from It takes effect only after the database retrieves the data. This means that only those column names can be used in your SELECT query. In addition, when you use table name connection to get column names, such as customer.id, the result will only contain the id column, so you must call ->indexBy(‘id’) without the table name prefix.

Recommended: "YII Tutorial"

The above is the detailed content of How to use indexBy() in Yii2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete