我有一个与此类似的结构,由REST Api返回:
{
"id": 1,
"type": "A",
"name": "blah, blah"
}
自然输出样本如下:
[
{
"id": 1,
"type": "A",
"name": "blah, blah"
},
{
"id": 1,
"type": "A",
"name": "blah, blah"
},
{
"id": 1,
"type": "B",
"name": "blah, blah"
},
{
"id": 1,
"type": "C",
"name": "blah, blah"
}
]
为方便起见,我宁愿以分组格式(围绕“类型”)进行分析,如下所示:
{
"A": [
{
"id": 1,
"name": "blah, blah"
},
{
"id": 1,
"name": "blah, blah"
}
],
"B": [
{
"id": 1,
"type": "B",
"name": "blah, blah"
}
],
"C": [
{
"id": 1,
"type": "C",
"name": "blah, blah"
}
]
}
在输入参数方面是否有一种常用的REST友好方式?
我有一个参数“response_mode”可能是FLAT或GROUPED,但我不确定它是否可以从RESTful观点出来。
答案 0 :(得分:0)
在php中我会这样排序:
<?php
$response = '[
{
"id": 1,
"type": "A",
"name": "blah, blah"
},
{
"id": 1,
"type": "A",
"name": "blah, blah"
},
{
"id": 1,
"type": "B",
"name": "blah, blah"
},
{
"id": 1,
"type": "C",
"name": "blah, blah"
}
]';
$jsonDecoded = json_decode($response);
$newResponse = array();
foreach($jsonDecoded as $jd) {
$newResponse[$jd->type][] = array(
"id" => $jd->id,
"type" => $jd->type,
"name" => $jd->name
);
}
echo json_encode($newResponse);