2012-01-05 101 views
0

我有定義了一些項目的下列的javascript陣列碼:過濾二維JavaScript數組

product[17564] = Array; 
product[17564][1245] = ['BL-2810', 'text1']; 
product[17564][1246] = ['BL2810AB', 'text2']; 
product[17564][1247] = ['BL2810AN', 'text3']; 

product[17563] = Array; 
product[17563][1238] = ['BK-2810', 'text4']; 
product[17563][1239] = ['BK2810AB', 'text5']; 

product[17565] = Array; 
product[17565][1253] = ['CK-2810', 'text6']; 
product[17565][1254] = ['CK2810AN', 'text7']; 

和我要篩選的物品的基礎上,「產品」的第一索引數組,由用戶動態設置。例如,如果用戶設定的號碼是「17563」,然後我要篩選具有「17563」以下項目作爲他們的第一個指數:

product[17563][1238] 
product[17563][1239] 

,並在隨後一個代碼只使用那些項目。 謝謝。

+3

該代碼是沒有做什麼,你認爲它是。將它們設置爲「Array」,而不是將其設置爲「[]」。 – Pointy 2012-01-05 14:36:56

+4

你應該使用對象而不是數組。你的問題是什麼?如何使用變量訪問屬性/索引?的 – 2012-01-05 14:37:13

+0

可能重複的[在一個關聯數組變量作爲指數 - 使用Javascript(http://stackoverflow.com/questions/4091257/variable-as-index-in-an-associative-array-javascript) – 2012-01-05 14:38:42

回答

0

看來你有產品類別,並且在每個類別中都有一些產品。

它也看起來像分類和產品有一種id,你用作數組索引。

我認爲你沒有使用正確的數據結構來存儲數據。

如果您只有3個類別的ID爲17883,17884和17885,會發生什麼? 您將以17886(計數位置0)位置的數組結束,以使用其中的3個位置。

您需要做的是存儲類別信息和產品信息,然後用這些對象填充數組的對象。

例如:

var categories = new Array(); 

var category1 = new Object(); 
category1.id = 17883; 
category1.products = new Array(); 
categories[0] = category1; 

var product1 = new Object(); 
product1.id = 1233; 
product1.code = 'BK-404'; 
product1.name = 'text3'; 

category1.products[0] = product1; 
// and so on 

要閱讀你會做的信息:

var userInput = //receive user input 
for(var i = 0; i < categories.length; i++){ 
    if(categories[i].id == userInput){ 
     return categories[i].products; 
    } 
    return null; //category not found 
} 
0

感謝您的幫助,它給了我使用JSON對象的線索。實際上,我有產品數據和每種產品具有的一些變體,並具有屬性(即類似於具有屬性的類別和產品的邏輯,如答案中)。

最後,我JSON編碼我最初的PHP數組(「$陣列」),從中我得到的數據,

$array_json=json_encode($array); 

,並傳遞給JavaScript(這是通過Smarty的完成,因爲我使用Smarty模板我的應用程序)。

$smarty->assign('array_json', $array_json); 

然後在smarty的模板文件,我創建一個JavaScript陣列出smarty的陣列:

var prd_array={$array_json}; 

和相續:

for (var product_id in prd_array) { 
      if(product_id == id) { 
       for (var variant_id in prd_array[product_id]) {      
        for (var some_attribute_id in prd_array[product_id][variant_id].attributes)  {       
         var variant_title = prd_array[product_id][variant_id].attributes[some_attribute_id].attribute_name;       
         document.myfrm.myselect.options[document.myfrm.myselect.options.length]=new Option("variant_title, variant_id, true, false);        
        } 
       } 
       break; 
      }    
     } 

爲說明上述情況,我迭代通過嵌套循環到多維數組的更深層次,以便獲得用戶所選產品變體的一些屬性值。'id'是值由用戶,這是針對每product_id值進行比較和匹配時,特定產品的變體被重複,與他們的atttributes屬性,它總是具有索引some_attribute_id單個元件一起,和中的一個所選擇的產品ID它的屬性是attribute_name其是用於在一動態填充選擇菜單顯示(連同variant_id值)的值中的一個。