Hi I have got a response from a query.The response is like:
{ 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" } ] }
Basically I want a function in php to format this response.The identical parent in the response in this case it is "summer",the data of the summer should print under it.i.e summer should be the parent of the data.The desired response is:
{ 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" } ] }
] }
The query response you posted does not seem to be valid JSON because the object properties are not quoted strings, you'll have to care about that to be able to parse the JSON string with json_decode()
. (See https://stackoverflow.com/a/6941739/846987 for example.)
This should generate your desired output:
<?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>';