首页 > 解决方案 > 在 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"
   }
]

那可能吗?如果是这样,我该怎么办?有更好的解决方案吗?

标签: phpjqueryjson

解决方案


使用 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
                )
        )
)

推荐阅读