Monday, May 14, 2012

PHP foreach / while / loop - how to traverse entire category hierarchy without database

I need to fetch the whole category tree hierarchy(ebay API) and print each category value without to use any database (i.e. mysql ). I've tried several approaches using foreach and while but my script dies after the top categories or at most after the first set of child categories . Here is my script :



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 = "http://open.api.ebay.com/Shopping?callname=GetCategoryInfo&appid=mihaibcdd-e1d6-40e3-933c-0feab57069f&siteid=0&CategoryID=$id&version=767&responseencoding=JSON&includeSelector=ChildCategories";
$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++;
}






No comments:

Post a Comment