2015-04-04 60 views
0

我有由PHP生成一個JavaScript陣列,使這個:將javascript數組鍵合併到內部數組中?

var sections = [ 
    section1 => 
    [name => anthony, email => [email protected]], 
    section1 => 
    [name => anthony, email => [email protected]], 
    section1 => 
    [name => anthony, email => [email protected]], 
    section2 => 
    [name => anthony, email => [email protected]], 
    section2 => 
    [name => anthony, email => [email protected]] 
] 

什麼使它的最好辦法:

var sections = [ 
    section1 => 
    [name => anthony, email => [email protected]], 
    [name => anthony, email => [email protected]], 
    [name => anthony, email => [email protected]], 
    section2 => 
    [name => anthony, email => [email protected]], 
    [name => anthony, email => [email protected]] 
] 

合併所有像鑰匙,並把所有的內部數組到同一個池。

因此,我可以循環每個部分作爲「部分」,而不是同一部分的部分。

+4

這不是JavaScript。 – Leo 2015-04-04 00:27:11

+0

這不是真正的代碼,它是一個例子。 – Anthony 2015-04-04 00:28:23

+4

好問題的步驟:1.發佈實際的JavaScript代碼。向我們展示你到目前爲止所嘗試的。 3.在演示中重現特定問題。 – elclanrs 2015-04-04 00:30:02

回答

0

你發佈的內容不是有效的JavaScript,所以你不明白你在找什麼結構。另外,您不應該讓PHP輸出有問題/重複的JavaScript,然後嘗試在稍後使用JavaScript進行清理,應該修改PHP以產生良好的JavaScript。將輸出存儲在PHP數組中不應該很難,而不是隻輸出它,然後只輸出唯一的元素(節)到JavaScript

這就是說,有一個簡單的修改您目前的輸出使其有效的JavaScript。我繼續追加"1""2"等的字符串末尾,使其明顯會發生什麼情況重複:

var sections = { 
    section1 : 
    {name : "anthony1", email : "[email protected]"}, 
    section1 : 
    {name : "anthony2", email : "[email protected]"}, 
    section1 : 
    {name : "anthony3", email : "[email protected]"}, 
    section2 : 
    {name : "anthony4", email : "[email protected]"}, 
    section2 : 
    {name : "anthony5", email : "[email protected]"}, 
}; 

console.log(sections.section1.name, sections.section1.email); // "anthony3" "[email protected]" 
console.log(sections.section2.name, sections.section2.email); // "anthony5" "[email protected]" 

沒有附加"1""2"等:

var sections = { 
    section1 : 
    {name : "anthony", email : "[email protected]"}, 
    section1 : 
    {name : "anthony", email : "[email protected]"}, 
    section1 : 
    {name : "anthony", email : "[email protected]"}, 
    section2 : 
    {name : "anthony", email : "[email protected]"}, 
    section2 : 
    {name : "anthony", email : "[email protected]"}, 
}; 

console.log(sections.section1.name, sections.section1.email); // "anthony" "[email protected]" 
console.log(sections.section2.name, sections.section2.email); // "anthony" "[email protected]"