【问题标题】:Query to group by the contents of the field按字段内容进行分组的查询
【发布时间】:2020-12-01 04:46:30
【问题描述】:

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

+----+--------------+-----------------+------------------------------+
| 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 位数字将其拆分为一个数组

【问题讨论】:

  • 您是在问如何将数据库表转换为 JSON 结构?
  • 您可以使用 substring 函数按字段的一部分进行分组。
  • @NevilleKuyt 不,这只是一个例子,我想根据前 3 位数字将其拆分为一个数组

标签: php sql arrays laravel data-structures


【解决方案1】:

这样的?

$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'];
}

工作example

参考

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    相关资源
    最近更新 更多