在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
问题是我不知道如何恢复我感兴趣的数据并将其放在正确的位置,因为类别的数量会随着时间的推移而增加
所以我想做类似的事情,将数据恢复为数据["invoice"] ["file_creation"]
和数据["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"
}
]
有可能吗?如果可以,该怎么办? 有更好的解决方案吗?
答案 0 :(得分:1)
此处是分别包含在发票和订单的结果列表中的代码。 在前端接收数据后,您可以使用简单的代码对所有项目进行分组:
var data = [
{
"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"
}
]
var categories = {
invoices: [],
orders: []
}
data.map((item) => {
if(item['File_category'] === 'order') {
categories.orders.push(item)
} else if(item['File_category'] === 'invoice') {
categories.invoices.push(item)
}
})
console.log(categories)
比起您,您就可以遍历特定类别,例如category.invoices或category.orders,然后轻松地将其附加到正文中。
答案 1 :(得分:1)
使用PHP代码执行此操作:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" />
<div class="form-group row">
<div style="float:left;" class="form-group col-xs-6">
<label>Date 1</label>
<input type="text" class="form-control" id="datepicker1"/>
</div>
<div style="float:left" class="form-group col-xs-6">
<label>Date 2</label>
<input type="text" class="form-control" id="datepicker2"/>
</div>
</div>
结果将是:
<?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);
?>