2014-12-19 93 views
0

我想這個數組轉換如下圖所示轉換數組的數組到JSON

array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"), 
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"), 
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"), 
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad")); 

成這種格式:

"3":{"Egypt":{"7":Tanta,"1000":"other"}},"80":{"India":{"0":"All","1":Ahmedabad}} 

我使用PHP和無法弄清楚如何我可以做這個。我已經使用json_encode。但結果不正確。我使用PHP作爲我的語言。

在此先感謝

+0

什麼是您的php代碼? – 2014-12-19 10:31:36

回答

1

之前轉換成JSON,你應該改變數組:

$array_countries_formated = array(); 

foreach ($array_countries as $item) 
{ 
    $array_countries_formated[$item['cntryValue']][$item['cntryLabel']][$item['value']] = $item['label']; 
} 

echo $array_countries_formated = json_encode($array_countries_formated, JSON_FORCE_OBJECT); 

結果:

{"3":{"Egypt":{"7":"Tanta","1000":"Other"}},"80":{"India":{"0":"All","1":"Ahmedabad"}}} 
+0

非常感謝帕特里克 – stacky 2014-12-19 11:30:08

0

試試這個...

<?php 
$array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"), 
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"), 
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"), 
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad")); 

$jsonString = json_encode($array_countries); 

print_r($jsonString); 
?> 

結果:

{"20":{"cntryValue":"3","cntryLabel":"Egypt","value":"7","label":"Tanta"},"21":{"cntryValue":"3","cntryLabel":"Egypt","value":"1000","label":"Other"},"22":{"cntryValue":"80","cntryLabel":"India","value":"0","label":"All"},"23":{"cntryValue":"80","cntryLabel":"India","value":"1","label":"Ahmedabad"}} 
+0

這不是我想要的結果 – stacky 2014-12-19 10:39:48

+0

你想要什麼類型的格式? – 2014-12-19 10:47:01

0

如果我正確理解你的要求輸出,下面應該做的伎倆:

$result = array(); 
foreach ($array_countries as $country) { 
    $cntryValue = $country["cntryValue"]; 
    if (!array_key_exists($cntryValue, $result)) { 
     $result[$cntryValue] = array(); 
    } 
    $result[$cntryValue][$country["cntryLabel"]] = array(); 
    $result[$cntryValue][$country["cntryLabel"]][$country["value"]] = $country["label"]; 
} 

echo json_encode($result) . "\n"; 

一點解釋:($array_countries)提供的陣列格式不同比到您要求的輸出。因此,它應該被轉換。這就是foreach循環所做的。格式化結果可以使用json_encode函數轉換爲json。