将对象数组中的类似项分组

时间:2015-10-15 00:47:14

标签: json laravel laravel-5 eloquent

您好我有以下JSON:

        [
    {
      "name": "Donation",
      "collection": {
        "name": "Donation Company 1",
        "collection": {
          "id": 1,
          "category": "Donation",
          "name": "Some Donation",
          "price": 10,
          "description": "Hahahaha",
          "company": "Donation Company 1"
        }
      }
    },
    {
      "name": "Donation",
      "collection": {
        "name": "Donation Company 1",
        "collection": {
          "id": 2,
          "category": "Donation",
          "name": "Another Donation",
          "price": 50,
          "description": "LoL",
          "company": "Donation Company 1"
        }
      }
    },
    {
      "name": "Insurance Company 1",
      "collection": {
        "name": "Hehe",
        "collection": {
          "id": 3,
          "category": "Insurance",
          "name": "Lorem Ipsum Solor",
          "price": 25,
          "description": "Lmao",
          "company": "Insurance Company 1"
        }
      }
    },
    {
      "name": "Insurance Company 2",
      "collection": {
        "name": "Donation Company 1",
        "collection": {
          "id": 5,
          "category": "Insurance",
          "name": "Sample Extra",
          "price": 500,
          "description": "Lorem ipsum dolor",
          "company": "Insurance Company 2"
        }
      }
    }
  ]

我在尝试将相似项目组合在一起时遇到问题,因为同一类别中的所有项目都出现在同一类别数组中。 在每个类别中,具有相同公司的所有项目最终都在同一公司阵列中。

这是我想要完成的一个示例,我使用在线编辑器构建JSON: expected-json-output-when-saved

我使用了laravel collect()辅助函数来构造我的对象数组,我在foreach循环中尝试了几种组合并且已经使用了几个小时但是仍然无法获得预期JSON返回。

1 个答案:

答案 0 :(得分:0)

假设您{J}字符串json_decode()并将其存储在$json变量中,您可以执行以下操作:

$collection = collect($json);

$collection = $collection->groupBy('collection.collection.category');

转储$collection变量以查看结果。