Php 如何最好地循环一个阵列,同时维护另一个阵列
我有一个包含4个元素的数组。此数组中的这些类别位于一个层次结构中,这样category2可以在category1中有多个实例,category3可以在category2中有多个实例,等等 我有一个web scrape函数,它有一个数组参数,我为每个类别调用它。该函数返回一个名为data的数组,该数组还包含类别的实际实例数组以及在后续类别的scrap调用中必须使用的数量不等的字符串元素。为了深入到我正在寻找的数据,我必须对类别1进行分类,将输出输入类别2,将输出输入类别3,等等,直到我最终在类别4的末尾得到了一个大数据集 但是,每个类别返回的数据集数组的每个元素也必须通过这个scrape函数。这是一个疯狂的多->多层次的混乱,我必须维持整个树的秩序 随着循环的进行,我还必须为每个实例维护各种各样的面包屑线索。例如,scrape category1,category1有3个实例,category2有10个实例,category3有25个实例。我搜索了category1,发现它有3个实例。然后,我获取这三个实例中每个实例的值,并将它们分别输入到category2的每个scrape中。如果这是成功的,那么我必须使用原始的3个category1实例值以及category2的10个实例的值,并将它们提供给category3 下面是我正在使用的代码示例:Php 如何最好地循环一个阵列,同时维护另一个阵列,php,Php,我有一个包含4个元素的数组。此数组中的这些类别位于一个层次结构中,这样category2可以在category1中有多个实例,category3可以在category2中有多个实例,等等 我有一个web scrape函数,它有一个数组参数,我为每个类别调用它。该函数返回一个名为data的数组,该数组还包含类别的实际实例数组以及在后续类别的scrap调用中必须使用的数量不等的字符串元素。为了深入到我正在寻找的数据,我必须对类别1进行分类,将输出输入类别2,将输出输入类别3,等等,直到我最终在类别4
$aCategoryOrder = array('category1','category2','category3','category4');
## First category web scrape ONLY needs the category name as a param
$aCatInput['category'] = $aCategoryOrder[0];
for ($i = 0; $i < count($aCategoryOrder); $i++) {
$sThisCat = $aCatInput['category'];
$sNextCat = $aCategoryOrder[$i + 1];
if ($i == 0) {
$aCatInput['category'] = $sThisCat;
} else {
$aCatInput['category'] = $sNextCat;
}##endif
$aScrape = webScrape($aCatInput);
## Capture the dataset out into another array to display later labeled
## with the category name.
$aOutput[$sThisCat]['data'] = $aScrape['data'];
## If this isn't category4 then we have to capture some of the output of the
## web scrape to use for the next category's web scrape input.
if ($aCatInput['category'] <> end($aCategoryOrder)) {
## Assign the name of the next category
$aCatInput['category'] = $sNextCat;
## Assign the view state to the next category
$sNextViewState = $aScrape['view_state'];
$aCatInput['view_state'] = $sNextViewState;
$sValName = $sThisCat . '_val';
## Separate out the actual data we're going to loop through
$aCatData = $aScrape['data'];
## This is where my problem is. Using this webScrape function again drives me
## nuts here. To loop through all of these instances is the exact same code
## above. However, I have to pass 1 to many different instances through it.
## There could be 40 or more elements in $aCatData that I need to run through
## the webScrape function. I'm trying to get away from having nested loops.
foreach ($aCatData as $sVal) {
$aCatInput[$sValName] = $sVal;
$aScrape = scrapeBookstore($aCatInput);
$aOutput[$sNextCat]['data'][] = $aScrape['data'];
$aCatInput['view_state'] = $aScrape['view_state'];
}##endforeach
}##endif
}##endfor
$aCategoryOrder=array('category1'、'category2'、'category3'、'category4');
##第一个类别web scrape只需要类别名称作为参数
$aCatInput['category']=$aCategoryOrder[0];
对于($i=0;$i
这就是我目前所拥有的。我相信这是一个很好的递归函数应用程序,但我无法在脑子里想清楚这整件事,以得到任何可靠的解决方案。这不是简单到将其包装在函数中,然后递归调用它吗?还是我遗漏了什么?对不起,我漏了一块。已编辑。我得到了答案,但我无法回答自己的问题。:/我使用嵌套的foreach循环。