我是php新手,为我的颜色响应创建web服务。它在我的web应用程序上工作得很好,因为我可以很容易地从它中获取数据,现在在android m卡住了。
我有这样的反应。
{
"#CCCCCC":[43.2,"SILVER"],
"#424153":[42.6,"GREY"],
"#999999":[13.7,"LIGHT GREY"]
}
我想把这个改成那样。
{
"colors":
[
{
"hex" : "#CCCCCC",
"percentgae" : "43.2",
"name" : "silver"
},
{
"hex" : "#424153",
"percentgae" : "43.2",
"name" : "grey"
},
{
"hex" : "#999999",
"percentgae" : "13.2",
"name" : "light grey"
}
]
}
你能告诉我怎么做吗?
谢谢。
可以使用下一个函数
<?php
function format($json) {
$colors = json_decode($json);
$result = [];
foreach ($colors as $color => $attributes) {
$result[] = [
'hex' => $color,
'percentagae' => $attributes[0],
'name' => $attributes[1]
];
}
return json_encode([ 'colors' => $result]);
}
$json = '{ "#CCCCCC":[43.2,"SILVER"], "#424153":[42.6,"GREY"], "#999999":[13.7,"LIGHT GREY"] }';
$expectation = '{"colors":[{"hex":"#CCCCCC","percentagae":43.2,"name":"SILVER"},{"hex":"#424153","percentagae":42.6,"name":"GREY"},{"hex":"#999999","percentagae":13.7,"name":"LIGHT GREY"}]}';
$response = format($json);
if ($response != $expectation) {
throw new Exception('FAIL');
}
echo 'SUCCESS';