PHP父/子类别

时间:2013-07-10 22:17:09

标签: php parsing tree

将下面的数据放在表格中:

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的表中插入一个类别,并为每个ProgramCode插入一个子类别,该类别包含它所包含的ProgramGroup的类别的parent_id,即(MAIN类别已经存在)

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 个答案:

答案 0 :(得分:1)

假设您的主数组在数组变量中,我们将调用$programs并且category_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);  
}

但是,如果可能的话,我真的会寻找其他优化原始设置的方法。这种设置似乎并不自然。