php - 在 Json/PHP 中为数组命名
问题描述
在 AJAX 中,由于此请求,我在数据库中按类别检索文档的最后日期(例如类别发票、订单等):
// In each category there can be several documents
$stmt = $bdd->prepare('SELECT file_name, max(file_creation) as file_creation, file_category
FROM all_files
WHERE ...
GROUP BY file_category');
$stmt ->execute(array(
...
));
$arr = $stmt->fetchAll();
echo json_encode($arr);
所以我用 JSON 把它找回来:
[
{
"File_name": "order_18"
"0": "order_18"
"File_creation": "2018-11-28"
"1": "2018-11-28"
"File_category": invoice "
"3": invoice "
}
{
"File_name": "order_18"
"0": "order_18"
"File_creation": "2018-11-25"
"1": "2018-11-25"
"File_category": "order"
"3": "order"
}
]
然后我想用 jquery 将每个数据放在正确的位置,如下所示:
$ ('#label-order').text('') // the text will have to be: 2018-11-25
$ ('#label-invoice').text('') // the text will have to be: 2018-11-28
问题是我不知道如何恢复我感兴趣的数据以将其放置在正确的位置,因为类别的数量会随着时间的推移而增加
所以我想做类似的事情,将数据恢复为 data["invoice"] ["file_creation"]
和 data ["order"] ["file_creation"]
:
[
"invoice": {
"File_name": "order_18"
"0": "order_18"
"File_creation": "2018-11-28"
"1": "2018-11-28"
"File_category": invoice "
"3": invoice "
}
"order": {
"File_name": "order_18"
"0": "order_18"
"File_creation": "2018-11-25"
"1": "2018-11-25"
"File_category": "order"
"3": "order"
}
]
那可能吗?如果是这样,我该怎么办?有更好的解决方案吗?
解决方案
使用 PHP 代码执行此操作:
<?php
//$arrays = $stmt->fetchAll();
$arrays=
[
[
"File_name"=>"order_18",
"File_creation"=>"2018-11-28",
"File_category"=>"invoice",
],
[
"File_name"=>"order_18",
"File_creation"=>"2018-11-25",
"File_category"=>"order",
]
];
foreach($arrays as $index=>$array)
{
if(isset($array["File_category"]))
{
$key=$array["File_category"];
unset($array["File_category"]);
$arrays[$key][] = $array;
unset($arrays[$index]);
}
}
print_r($arrays);
//echo json_encode($arrays);
?>
结果将是:
Array
(
[invoice] => Array
(
[0] => Array
(
[File_name] => order_18
[File_creation] => 2018-11-28
)
)
[order] => Array
(
[0] => Array
(
[File_name] => order_18
[File_creation] => 2018-11-25
)
)
)
推荐阅读
- reactjs - onClick 触发所有子菜单,而不仅仅是被点击的菜单
- python-2.7 - python中的abstractproperty + classmethod装饰器
- android - ADB Shell 无权访问
- azure - 尝试从 ACR 拉图像时 Azure 发布管道失败
- java - Lucene 同时搜索存储和未存储的字段
- asynchronous - 如何修复“FileSystemException:当前正在等待异步操作”?
- javascript - 客户端 JS 和服务器端 C# 通信
- c++ - C++ 中的双重行为很奇怪
- database - 分片后我的 mongodb 数据库大小增加了一倍?
- ruby-on-rails - Docker 和 Rails:无法访问日志文件