php - 按字段内容进行分组的查询
问题描述
我需要帮助才能按字段内容进行分组。我有以下数据库:
+----+--------------+-----------------+------------------------------+
| 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 个数字将其拆分为一个数组
解决方案
像这样的东西?
$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 - 检查数组中的键是否存在
推荐阅读
- sql - 在 id 级别显示最旧的值和最新的值
- rust - 尝试延迟关联类型时“溢出评估需求”
- combobox - 我可以删除 ComboBoxListViewSkin 创建的“胡萝卜”(倒三角形)吗?
- python - 如何将张量划分为 NXN 块并再次从这些块中重建第一个?
- sql - 需要为具有 varchar 和 date 数据类型的多个条件创建 case 语句
- r - 如何从html页面下载多个同名文件?
- c - 我正在为纸牌游戏编写代码。在我的交易卡功能中,程序卡住了,我无法确定原因
- ms-access-2007 - 如何在 MS Access 2007 中使用 concatRelated
- java - java中是否有以下Aes加密函数的Dart等价物
- python - 如果 OS 应用缩放因子,ImageGrab/pyscreenshot 不会捕获全屏