自定义查询响应数组

时间:2019-06-17 15:04:34

标签: php arrays json sorting arraylist

我有一个JSON响应可以根据我们的需要进行定制

响应如下所示,其中包含带有数据的多个数组

但是我想对诸如MAIN之类的单个类别进行分类,并在其值中的数组中显示所有相关内容

[
  {
    "Main": [
      "Map View"
    ],
    "Reports": [
      "Sensor Data Report"
    ],
    "Configuration": [
      "Region Configuration"
    ],
    "Admin": [
      "Customer Management"
    ]
  },
  {
    "Main": [
      "Map View"
    ],
    "Reports": [
      "Sensor Data Report"
    ],
    "Configuration": [
      "Region Configuration"
    ],
    "Admin": [
      "Device Management"
    ]
  }
]

但是我需要这样的东西

{
  "Main": [
    "Dashboard",
    "Devices"
  ],
  "Reports": [
    "Alert Report",
    "MOnthly Reports"
  ],
  "Configuration": [
    "Region Configuration",
    "Device Management"
  ]
}

1 个答案:

答案 0 :(得分:1)

一个选项可能是,因为您的第一个包含数据的多个数组每个条目都包含一个项目,所以使用foreach的2倍并收集同一键的所有值。

由于示例数据包含重复值,因此您可以使用array_unique

$result = [];
foreach ($arrays as $array)
    foreach ($array as $k => $v)
        array_key_exists($k, $result) ? $result[$k][] = $v[0] : $result[$k] = [$v[0]];

$result = array_map('array_unique', $result);

print_r($result);

查看php demo

结果

Array
(
    [Main] => Array
        (
            [0] => Map View
        )

    [Reports] => Array
        (
            [0] => Sensor Data Report
        )

    [Configuration] => Array
        (
            [0] => Region Configuration
        )

    [Admin] => Array
        (
            [0] => Customer Management
            [1] => Device Management
        )

)