使用动态键值对数组进行分组?

时间:2017-10-25 15:32:33

标签: php arrays json

我有JSON数组值,如下所示,

{
  "test_details": [
    {
      "test_id": "001",
      "test_name": "Blood Test",
      "group_name": "Group 1",
      "package_details": [
        {
          "package_name": "master health checkup",
          "package_id": "1"
        },
        {
          "package_name": "special camp package",
          "package_id": "2"
        }
      ]
    },
    {
      "test_id": "002",
      "test_name": "haemoglobin",
      "group_name": "Group 2",
      "package_details": [
        {
          "package_name": "master health checkup",
          "package_id": "1"
        }
      ]
    },
    {
      "test_id": "003",
      "test_name": "creatine test",
      "group_name": "Group 2",
      "package_name": null
    }
  ]
}

在上面的JSON中,我想通过键package_name对值进行分组,这意味着我想根据包名称对测试列表进行排序。

我已按功能尝试了几个数组,但对于动态键package_name,它无效。

我的最终输出JSON将是:

{
  "test_details": {
    "master health checkup": [
      {
        "test_id": "001",
        "test_name": "Blood Test",
        "group_name": "Group 1",
        "package_details": [
          {
            "package_name": "master health checkup",
            "package_id": "1"
          },
          {
            "package_name": "special camp package",
            "package_id": "2"
          }
        ]
      },
      {
        "test_id": "002",
        "test_name": "haemoglobin",
        "group_name": "Group 2",
        "package_details": [
          {
            "package_name": "master health checkup",
            "package_id": "1"
          }
        ]
      }
    ],
    "special camp package": [
      {
        "test_id": "001",
        "test_name": "Blood Test",
        "group_name": "Group 1",
        "package_details": [
          {
            "package_name": "master health checkup",
            "package_id": "1"
          },
          {
            "package_name": "special camp package",
            "package_id": "2"
          }
        ]
      }
    ]
  }
}

在这里你可以看到主健康检查有2个测试,而且特殊营地包有1个测试。怎么实现这个?当数组键是动态的时候如何应用数组?

1 个答案:

答案 0 :(得分:0)

解码JSON后,迭代test_details。如果测试具有package_details属性,则迭代该属性并使用每个包名称作为键将测试分配给结果数组。

$data = json_decode($json);

foreach ($data->test_details as $test) {
    if (isset($test->package_details)) {
        foreach ($test->package_details as $package) {
            $result['test_details'][$package->package_name][] = $test;
        }
    }
}

echo json_encode($result);