【问题标题】:modify json response in php?在 php 中修改 json 响应?
【发布时间】:2014-09-16 06:46:28
【问题描述】:

我是 php m 的新手,为我的颜色响应创建 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"
               }
            ]
}

你能告诉我怎么做吗?

谢谢。

【问题讨论】:

  • 你能分享你的尝试吗?
  • 是的,请使用您目前拥有的代码进行更新以生成您当前拥有的数组结构。
  • 我有一个像“#CCCCCC”=>“23”一样返回的二维数组,我有一个返回十六进制值名称“#CCCCCC”=>“灰色”的数组。我使用 $result = array_merger_recursive ($array1,$array2) 合并两个数组。这给了我这样的数组(Array [#CCCCCC]=> array(0 => 23, 1= > Grey))。现在我使用 json_encode($result) 将 $result 转换为 json。

标签: php android arrays json multidimensional-array


【解决方案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';

【讨论】:

  • 它可以帮助我获得所需的结果。所以我接受你的回答:干杯
猜你喜欢
  • 2016-04-10
  • 2020-01-19
  • 2013-03-04
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多