您好我收到了来自查询的回复。回复如下:
{ 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中使用一个函数来格式化这个响应 在这种情况下,响应中的父母是#34;夏天",数据 夏天应该在它下面打印。夏天应该是父母 数据。所需的答案是:
{ 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" } ] }
] }
答案 0 :(得分:0)
您发布的查询响应似乎不是有效的JSON,因为对象属性不是带引号的字符串,您必须关心它以便能够使用json_decode()
解析JSON字符串。 (例如,请参阅https://stackoverflow.com/a/6941739/846987。)
这应该会产生您想要的输出:
<?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>';