嗨,我收到了一个查询的响应。回复如下:
{ 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中的一个函数来格式化这个响应。这个在这种情况下,响应中的同一父母是"夏天",数据夏天的名字应该印在下面。也就是说,夏天应该是父母的数据。所需的响应是:
{ 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_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>';