2014-07-24 111 views
-2

我是php m中的新手,爲我的顏色響應創建web服務。它在我的web應用程序上效果很好,因爲我現在可以在android m中輕鬆獲取數據。在PHP中修改json響應?

我有這樣的迴應。

{ 

     "#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" 
       } 
      ] 
} 

你能告訴我該怎麼做。

謝謝。

+0

你能分享你試過嗎? –

+0

是的,請更新您目前使用的代碼來生成當前的數組結構。 –

+0

我有二維數組,返回像「#CCCCCC」=>「23」,我有一個返回十六進制名稱「#CCCCCC」=>「灰色」的數組。我使用$ result = array_merger_recursive($ array1,$ array2)合併兩個數組。這給了我這樣的數組(Array [#CCCCCC] => array(0 => 23,1 => Gray))。現在我使用json_encode($ result)將$ result轉換爲json。 – umair

回答

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'; 
+0

它可以幫助我得到我需要的結果。所以我接受你的答案:歡呼聲 – umair