Aug 222012
 
error_reporting(E_ALL);
ini_set('display_errors', '1');

require_once( 'app/Mage.php');
echo '<pre>';
$app = Mage::app();

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
 
	$readresult = $write->query("SELECT * FROM table limit 1 ");
	$row = $readresult->fetch();
	$SKU = $row['SKU']; 
	if($SKU=='')
	{
		echo 'no Record';
		exit;
	}
	
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$SKU);

echo "Product SKU : ".$SKU."<br>";

if ($product) 
{
	if ($product->getId()) 
	{
		/*$product->setCategoryIds(array(393));
			$product->save();
			exit;*/
		echo "Product ID : ".$product->getId()."<br>";
		echo "Product Name : ".$product->getName()."<br>";
		$categoryIds = $product->getCategoryIds();
		if (is_array($categoryIds) and count($categoryIds) > 0) 
		{
			$theMaster = array();
			print_r($categoryIds);
			$theMaster = array_merge($theMaster,$categoryIds);
			foreach($categoryIds as $curProductCatID  )
			{
				
				echo "Product Category ID : ".$curProductCatID."<br>";
				$theCategory = Mage::getModel('catalog/category')->load($curProductCatID);
			
				if($theCategory->getParentId())
				{
					$cat_array= array($curProductCatID);
					$cat_array = getParentTopCategory($theCategory,$cat_array);
					$final_array= array_reverse($cat_array);
					print_r($final_array);
					$theMaster = array_merge($theMaster,$final_array);
					
				}
				else
				{
					echo 'Parent category  not found<br>';
				}
			}
			echo "master array :";
			print_r($theMaster);
			echo '<br>';
			$tmpA = array();
			
			$theMaster = array_unique ($theMaster);
			foreach($theMaster as $item)
			{
				$tmpA[] = $item;
			}
			echo "master unique array :";
			print_r( $tmpA);
			echo '<br>';
			$product->setCategoryIds($tmpA);
			$product->save();
		}
	}
	else
	{
		echo 'Product not found';
	}
} 

function  getParentTopCategory($category,$cat_array)
{
	echo $category->getName()."<br>";
	if($category->getLevel() == 2)
	{
		$cat_array[]=$category->getParentId();
		return $cat_array;
	}
	else
	{
		
		$parentCategory = Mage::getModel('catalog/category')->load($category->getParentId());
		if($category->getParentId())
		{
			$cat_array[]=$category->getParentId();
			return getParentTopCategory($parentCategory,$cat_array);
		}
		else
		{
			return $cat_array;
		}
	}
}