将 json 响应格式化为 parent 和 child

format json response into parent and child

嗨,我收到了来自 query.The 的回复:

{ data: [
       {
       parent: "summer",
       image: "template/assets/x354.jpg",
       productName: "United Colors of Benetton"    },   {   parent: "autumn",   image: "template/assets/x354.jpg",   productName: "United
   Colors of Benetton" }, { parent: "summer", image:
   "template/assets/x354.jpg", productName: "Puma Running Shoes" } ] }

基本上我想要 php 中的一个函数来格式化这个 response.The 在这种情况下,响应中的相同 parent 是 "summer",数据 夏天应该打印在 it.i.e 夏天应该是 parent data.The 期望的响应是:

{ data: [
       {
        parent: "autumn",
        image: "template/assets/x354.jpg", productName: "United Colors of Benetton" }, { parent: "summer" [{ image:
   "template/assets/x354.jpg", productName: "United Colors of Benetton"
   }, { image: "template/assets/x354.jpg", productName: "Puma Running
   Shoes" } ] }

   ] }

您发布的查询响应似乎无效 JSON 因为对象属性不是带引号的字符串,您必须注意这一点才能解析 JSON 字符串json_decode()。 (例如,参见 。)

这应该会生成您想要的输出:

<?php

$json = <<<EOT
{
    "data": [
        {
            "parent": "summer",
            "image": "template\/assets\/x354.jpg",
            "productName": "United Colors of Benetton"
        },
        {
            "parent": "autumn",
            "image": "template\/assets\/x354.jpg",
            "productName": "United Colors of Benetton"
        },
        {
            "parent": "summer",
            "image": "template\/assets\/x354.jpg",
            "productName": "Puma Running Shoes"
        }
    ]
}
EOT;
$jsonObject = json_decode($json);

$categories = array();
foreach($jsonObject->data as $element) {
  if ( ! isset($categories[$element->parent])) {
    $categories[$element->parent] = array();
  }
  $categories[$element->parent][] = $element;
  unset($element->parent);
}

echo '<pre>' . json_encode($categories, JSON_PRETTY_PRINT) . '</pre>';