2013-07-10 69 views
-1

有以下數據表中的:PHP父/子類別

programgroup,programcode 
"C1","AM" 
"C1","CC" 
"C1","CC" 
"C1","CC" 
"C1","CC" 
"C1","CC" 
"C1","CC" 
"C1","CP" 
"C1","CP" 
"C1","CP" 
"C1","CP" 
"C1","PL" 
"C1","PL" 
"C1","PL" 
"C1","PL" 
"C1","PL" 
"C4","2IC" 
"C4","2IC" 
"C4","2IC" 
"C4","2IC" 
"C4","2IC" 
"C4","AO" 
"C4","AO" 
"C4","AO" 
"C4","IP" 
"C4","IP" 
"C4","PA" 
"C4","PA" 
"C4","PM" 
"C4","PR" 
"C4","PR" 
"C4","SR" 
"C4","WH3" 

我在看數據,並遍歷記錄,我需要在一個表中插入一個類別爲每個ProgramGroup和一個孩子類別具有類別的PARENT_ID它被包含在,即(主要類別將已存在)的ProgramGroup每個的程序代碼

category_id, value, parent_id 
0, "MAIN", null 
1, "C1", 0 
2, "AM", 1 
3, "CC", 1 
4, "CP", 1 
5, "PL", 1 
6, "C4", 0 
7, "21C", 6 
8, "AO", 6 
9, "IP", 6 
10, "PA", 6 
11, "PM", 6 
12, "PR", 6 
13, "SR", 6 
14, "WH3", 6 

誰能告訴我如何做到這一點在PHP僞代碼?

回答

1

假設你的主陣列是一個數組變量,我們將調用$programscategory_id是自動遞增列:

$program_groups = array_keys($programs); // will store as array([0] => C1, [1] => C4) 
$program_codes = array_unique($programs); // will store as array([0] => AM, [1] => CC, [7] => CP, ..) 

foreach($program_groups as $index => $key) { 
    // INSERT INTO table (category_id, value, parent_id) VALUES ($index, $key, '0'); 
} 

foreach($program_codes as $index => $value) { 
    $parent_id = array_search($programs, $index); 
    // INSERT INTO table (value, parent_id) VALUES ($value, $parent_id); 
} 

不過說真的我會尋找其他方式來優化您的原始設置,如果在所有可能。這種設置看起來不自然。