修改php中的json响应?

时间:2014-07-24 15:47:17

标签: php android arrays json multidimensional-array

我是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"
               }
            ]
}
你可以告诉我怎么做。

感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用下一个功能

<?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';