如何动态构建多维数组?
我知道这是一个开放式的问题,但我有一段时间了。
我所拥有的是一个数组需要使数组添加另一个子节点的可能性。
Array(
[0] => Array
(
[parentID] => 0
[component] => 23941/01
[decoration] =>
[hasChild] => T
[proccessed] => T
[cmp0] => Array
(
[parentID] => 0
[component] => COLC01
[decoration] =>
[hasChild] => F
[proccessed] => T
)
[cmp1] => Array
(
[parentID] => 0
[component] => PPH
[decoration] =>
[hasChild] => F
[proccessed] => T
)
)
[1] => Array
(
[parentID] => 1
[component] => 23930/20SB
[decoration] =>
[hasChild] => T
[proccessed] => T
[cmp0] => Array
(
[parentID] => 1
[component] => 23930/20
[decoration] =>
[hasChild] => T
[proccessed] => F
)
)
[2] => Array
(
[parentID] => 2
[component] => SC070400SB
[decoration] =>
[hasChild] => T
[proccessed] => T
[cmp0] => Array
(
[parentID] => 2
[component] => SC070400
[decoration] =>
[hasChild] => F
[proccessed] => T
)
))
我使用简单数组推送生成的外部数组[0,1,2]。当我开始遍历数组以达到较低级别时,我遇到的问题不仅仅是深层了。
这是我的主要问题:如何动态添加元素到数组,同时仍然能够检查键值以查看是否应该更深入? processed和hasChild标志告诉我可以更深入,但isset和array_key_exists似乎不适用于新添加的元素。事实上,当我将数组打印到屏幕时,它甚至没有显示任何元素,如[cmp0] ...
我不确定我的代码会提供多少帮助,但我会在此处进行浏览。
function explodeBOM(&$BOMArray,$library,$sonar){
$saveKey = '';
$childCounter = 0;
$childKey = '';
foreach($BOMArray as &$bomLine){
$childKey = 'cmp' . (string)$childCounter;
while(array_key_exists($childKey,$bomLine)){
explodeBOM($bomLine[$childKey],$library,$sonar);
}
if($bomLine['proccessed'] == "F"){
$saveKey = $bomLine['parentID'];
$bomItems = getBOM($bomLine['component'],$bomLine['decoration'],$library,$sonar);
foreach($bomItems as $newBomLine){
$itemMasterInfo = getItemMasterInfo($newBomLine['BMCMP#'],$newBomLine['BMCMD#'],$library,$sonar);
if($itemMasterInfo['ITPRTC'] != 'P' AND $itemMasterInfo['ITPRTC'] != 'C'){
// add it to the array
$componetArray = array();
$componetArray['parentID'] = $saveKey;
$componetArray['component'] = $newBomLine['BMCMP#'];
$componetArray['decoration'] = $newBomLine['BMCMD#'];
$componetArray['hasChild'] = parentOrChildBOM($newBomLine['BMCMP#'],$newBomLine['BMCMD#'],$library,$sonar);
if ($componetArray['hasChild'] == 'F'){
$componetArray['proccessed'] = 'T';
}else{
$componetArray['proccessed'] = 'F';
}
//array_push($bomLine,$componetArray);
$childKey = 'cmp' . (string)$childCounter;
$childCounter++;
$bomLine[$childKey] = $componetArray;
$bomLine['proccessed'] = 'T';
reset($BOMArray);
}
}
$childCounter = 0;
}
}
}