首页 > 解决方案 > 按字段内容进行分组的查询

问题描述

我需要帮助才能按字段内容进行分组。我有以下数据库:

+----+--------------+-----------------+------------------------------+
| id | depart_kode  |    depart_task  |            value             |
+----+--------------+-----------------+------------------------------+
| 1  |     001      |  Create Profil  |  Some Value                  |
| 2  |     001.12   |  Create Profil  |  Some Value                  |
| 3  |     001.452  |  Create Profil  |  Some Value                  |
| 4  |     002.914  |  Create Profil  |  Some Value                  |
| 5  |     002      |  Create Profil  |  Some Value                  |  
| 6  |     003      |  Create Profil  |  Some Value                  |
+----+--------------+-----------------+------------------------------+

我需要查询我按depart_kode分组的地方,我应该像这样以json格式打印前3位数字

  "001":[
    {
    "depart_kode":"001,
    and other 
    },
    {
   "depart_kode":"001.12"
    },
    ],
    "002":[
    {
     "depart_kode":"002"
    }
]

类似的东西,最重要的是,它们将根据前 3 个数字(如 001)分组在一个数组中。json 只是一个示例,我想根据前 3 个数字将其拆分为一个数组

标签: phpsqlarrayslaraveldata-structures

解决方案


像这样的东西?

$departs = [];
foreach ($sqlRows as $row) {
    $departKey = substr($row['depart_kode'], 0, 3);
    
    if (!array_key_exists($departKey, $departs)) {
        $departs[$departKey] = [];
    }
    
    $departs[$departKey][] = $row['depart_kode'];
}

工作示例

参考

  • substr - 获取字符串的特定部分(我们示例中的前 3 个字符)
  • array_key_exists - 检查数组中的键是否存在

推荐阅读