2015-10-05 170 views
0

您好我有一個像下面的維生素A JSON數據格式,menrals,我需要合併單個陣列內的同一JSON按鍵陣列,合併相同的密鑰JSON數據

[ 
    { 
     Vitamins: [ 
      "Please explain details about vitamins.", 
      "Vitamin is a vitamin.:P:D", 
      "7" 
     ] 
    }, 
    { 
     Vitamins: [ 
      "i need more explanation about VitaminD. bcoz i'm new to medicine field ", 
      "i don't know the ans.. :P", 
      "7" 
     ] 
    }, 
    { 
     Minerals: [ 
      "i need more info about Minerals!", 
      "Minerals are found in soils", 
      "8" 
     ] 
    } 
] 

,但我需要改變,因爲,請幫助如何合併它

[ 
    { 
     Vitamins: [ 
      { 
       "Please explain details about vitamins.", 
       "Vitamin is a vitamin.:P:D", 
       "7" 
      }, 
      { 
       "i need more explanation about VitaminD. bcoz i'm new to medicine field ", 
       "i don't know the ans.. :P", 
       "7" 
      } 
     ] 
    }, 
    { 
     Minerals: [ 
      "i need more info about Minerals!", 
      "Minerals are found in soils", 
      "8" 
     ] 
    } 
] 

任何幫助表示感謝,提前致謝。

+3

你有什麼這麼遠嗎?請張貼你已經試圖解決它的代碼。 –

+0

你只需要格式化它的權利? –

+0

是的Praveen,但這些是我動態獲得,以防萬一我可以有10組相同的密鑰,我需要合併它 – ManoharSingh

回答

4

使用一個簡單的循環foreach

first = [ 
    { 
    Vitamins: [ 
     "Please explain details about vitamins.", 
     "Vitamin is a vitamin.:P:D", 
     "7" 
    ] 
    }, 
    { 
    Vitamins: [ 
     "i need more explanation about VitaminD. bcoz i'm new to medicine field ", 
     "i don't know the ans.. :P", 
     "7" 
    ] 
    }, 
    { 
    Minerals: [ 
     "i need more info about Minerals!", 
     "Minerals are found in soils", 
     "8" 
    ] 
    } 
]; 
last = {}; 
for (var i in first) { 
    if (typeof last[i] == "undefined") 
    last[i] = []; 
    last[i].push(first[i]); 
} 
console.log(last); 

入住JSBin例如控制檯。

JSBin:http://jsbin.com/guruxesaco/edit?js,console

+0

我需要合併維生素的價值在同一個密鑰內,但是這個循環再次形成相同的json格式 – ManoharSingh

+0

我不明白。它做你想要的。你在說什麼關鍵?你檢查了控制檯嗎? –

+0

感謝您的回覆,我的意思是維生素是關鍵,礦物質是關鍵,請檢查我上面發佈的輸出格式。 – ManoharSingh

0

您好我回答了我的問題

$t = [ 
    { 
     Vitamins: [ 
      "Please explain details about vitamins.", 
      "Vitamin is a vitamin.:P:D", 
      "7" 
     ] 
    }, 
    { 
     Vitamins: [ 
      "i need more explanation about VitaminD. bcoz i'm new to medicine field ", 
      "i don't know the ans.. :P", 
      "7" 
     ] 
    }, 
    { 
     Minerals: [ 
      "i need more info about Minerals!", 
      "Minerals are found in soils", 
      "8" 
     ] 
    } 
] 

$result = array(); 

$s=0; 



foreach($t as $t1=>$t2) 
{ 

    foreach($t2 as $t3=>$t4) 
    { 

     $result[$t3][$s]=$t4; 
     $s++; 

    } 
} 

,其結果是 回聲json_encode($結果);

{ 
Vitamins: [ 
{ 
ques: "Please explain details about vitamins.", 
ans: "Vitamin is a vitamin.:P:D" 
}, 
{ 
ques: "i need more explanation about VitaminD. bcoz i'm new to medicine field...", 
ans: "Vitamin D is found in Sun so please take sun bath daily." 
} 
], 
Minerals: { 
2: { 
ques: "i need more info about Minerals!", 
ans: "Minerals are found in soils" 
} 
} 
} 

感謝您的答案:)