我需要获取整个类别树层次结构(ebay API)并打印每个类别值而不使用任何数据库(即mysql)。我尝试了几种使用foreach的方法,但是我的脚本在顶级类别之后死亡,或者最多在第一组子类别之后死亡。
这是我的剧本:
set_time_limit('0');
error_reporting(E_ALL);
## get categories allow us to traverse through categories
//getcategorycall call to return the categories based on the category id
function GetCategoryInfo($id) {
$URL = "api.example.com";
$response = json_decode(file_get_contents($URL), true);
//check if the request is returned with success
$Ack = $response['Ack'];
if ($Ack !== 'Success') {
echo "error $Ack";
exit();
}
//get category array
$CategoryArray = $response['CategoryArray']['Category'];
return $CategoryArray;
}
$CategoryID_top = '-1';
$CategoryInfo = GetCategoryInfo($CategoryID);
//traverse top categories
//we need to count the categories and start from 1 due the fact the requested category(e.g. root) is included in the response
$top_count = count($CategoryInfo);
$top_i = 1;
while ($top_i <= $top_count) {
$Category = $CategoryInfo[$top_i];
# print_r($Category);
# exit();
$CategoryID = $Category['CategoryID'];
$CategoryName = $Category['CategoryName'];
$LeafCategory = $Category['LeafCategory'];
echo " Top category:: $CategoryID\n $CategoryName\n $LeafCategory\n<br>";
//traverse child categories that are not leaf until it reaches the leaf categories
if (empty($LeafCategory)) {
echo "this is not a leaf category";
$CategoryInfo = GetCategoryInfo($CategoryID);
$child_count = count($CategoryInfo);
$child_i = 1;
while ($child_i <= $child_count) {
$Category = $CategoryInfo[$child_i];
$CategoryID = $Category['CategoryID'];
$CategoryName = $Category['CategoryName'];
$LeafCategory = $Category['LeafCategory'];
echo " Child category :: $CategoryID\n $CategoryName\n $LeafCategory\n<br>";
$child_i++;
}
}
$top_i++;
}
答案 0 :(得分:0)
据我所知,你不应该在你的内循环中替换$ CategoryInfo变量(而是选择一个不同的名称),因为它可能搞砸了。
您可能需要获取太多数据,这将花费很长时间并导致脚本停止在预定义的限制。使用set_time_limit()函数将限制设置为更高的值(例如几分钟)。
另外,为简化起见,请使用以下代码:
$top_count = count($CategoryInfo);
$top_i = 1;
while ($top_i <= $top_count) {
$Category = $CategoryInfo[$top_i];
...
$top_i++;
}
可以替换为:
foreach ($CategoryInfo as $Category) {
...
}