php - 使用php在json中分组相同的名称
问题描述
我正在尝试使用顶点图表创建时间线。我不能从字面上打印 Json 数据。
$temp[$r["Durum"]]['data'][] = array(
'x' => $r['Basladı'],
'y' => array(
strtotime($r['Saat']),
strtotime($r['Bitis'])
)
);
输出
{
"P": {
"data": [
{
"x": "Basladi",
"y": [
1602418875,
1602418884
]
},
{
"x": "Basladi",
"y": [
1602418887,
1602418902
]
},
]
}
}
我想要的输出
{
{
"name" : "P",
"data": [
{
"x": "Basladi",
"y": [
1602418875,
1602418884
]
},
{
"x": "Basladi",
"y": [
1602418887,
1602418902
]
},
]
}
}
解决方案
这是一个代码示例,其中包含一些适合您的示例输入。
示例数据(在您的情况下是数据库中的数据):
$yourdata = array(
array(
'Durum' => 'p',
'Basladı' => 'Basladı',
'Saat' => '12.12.2020',
'Bitis' => '12.12.2020'
),
array(
'Durum' => 'p',
'Basladı' => 'Basladı',
'Saat' => '12.12.2020',
'Bitis' => '12.12.2020'
),
array(
'Durum' => 's',
'Basladı' => 'Basladı',
'Saat' => '12.12.2020',
'Bitis' => '12.12.2020'
)
);
代码片段:
// create empty temp array for the result
$temp = [];
// loop through your data (only an example - replace with your data)
foreach($yourdata as $r) {
// defines a temp data array to add
$temp_data = array(
'x' => $r['Basladı'],
'y' => array(
strtotime($r['Saat']),
strtotime($r['Bitis'])
)
);
// check if there is already an entry with that name
if(($key = array_search($r["Durum"], array_column($temp, 'name'))) !== false) {
// if there is, only add the data to it
$temp[$key]['data'][] = $temp_data;
} else {
// otherwise push a new array with the name and data to temp
$temp[] = array(
'name' => $r["Durum"],
'data' => array($temp_data)
);
}
}
var_dump($temp); // process with the data
变量的内容$temp
:
Array
(
[0] => Array
(
[name] => p
[data] => Array
(
[0] => Array
(
[x] => Basladı
[y] => Array
(
[0] => 1607731200
[1] => 1607731200
)
)
[1] => Array
(
[x] => Basladı
[y] => Array
(
[0] => 1607731200
[1] => 1607731200
)
)
)
)
[1] => Array
(
[name] => s
[data] => Array
(
[0] => Array
(
[x] => Basladı
[y] => Array
(
[0] => 1607731200
[1] => 1607731200
)
)
)
)
)
推荐阅读
- reactjs - 如何避免子组件的重新渲染
- jquery - jQuery map 基于属性值和排序
- firebase - “DocumentSnapshot”不是“String”类型的 subpyte
- javascript - 仅对数组 javascript 中的值进行分页
- hadoop - 有没有办法在使用 HDFS 文件目标推送到 SSIS 中的 hdfs 时为文件提供时间戳
- python - 从 flask.session 读取返回一个空列表
- c# - Azure 不加载捆绑包
- php - 使用 Lumen 进行简单的访问授权
- windows - 有没有办法检测窗口是否已闪烁?
- django - Django 3.0.9 错误消息 course.File.file: (models.E006) 字段 'file' 与模型 'courses.itembase' 中的字段 'file' 冲突