php - Magento : Category Name instead of category ids in category path.

标签 php performance magento magento-1.7

我正在尝试根据 magento 中的产品 ID 在类别路径中获取类别名称。

假设我的产品 ID = 1,并且我在其中定义了 category5 (id = 5),并且我得到了类似 2/3/5 的类别路径。我需要像 category2/category3/category5 这样的类别路径,而不是这种类型的类别路径。这意味着我需要路径中的类别名称而不是类别 ID。我通过使用以下代码得到了这个但是它花费了很多时间。我需要减少处理时间。

请就如何减少处理时间给我建议。

$category_model = Mage::getModel('catalog/category');  
$product_model = Mage::getModel('catalog/product'); 
$all_cats = array();
$product_model->reset();
$_product = $product_model->load($entityId);
$all_cats = $product_model->getCategoryIds($_product); 
$main_cnt = count($all_cats);
$cat_str_main = ''; 
$j = 0;
foreach($all_cats as $ac)
{
    $root_category = $category_model->load($ac);
    $cat_path = $root_category->getPath();
    $cat_arr = explode("/",$cat_path);
    $cnt = count($cat_arr);
    $cat_str = '';
    $main_str = '';
    $i=0;
    foreach($cat_arr as $ids)
    {
                $root_category = $category_model->load($ids); //load root catalog
        if($i == 2)
        {
            $cat_str = $category_model->getName();
        }
        else if($i > 2)
        {
            $cat_str = $cat_str."/".$category_model->getName();
        }
        $i = $i+1;
    }
    if($j < 1)
    {
        $cat_str_main = $cat_str;
    }
    else 
    {
        $cat_str_main = $cat_str_main .",".$cat_str;
    }
    $j = $j+1;
}

谢谢.....

最佳答案

您应该使用类别集合而不是为每个类别加载以减少数据库查询。

编辑: 我已经给你写了一个代码示例。我假设您有类别的类别 ID,您希望将其路径名称作为 $categoryId:

$category = Mage::getModel('catalog/category')->load($categoryId);
$collection = $category->getResourceCollection();
$pathIds = $category->getPathIds();
$collection->addAttributeToSelect('name');
$collection->addAttributeToFilter('entity_id', array('in' => $pathIds));
$result = '';
foreach ($collection as $cat) {
    $result .= $cat->getName().'/';
}

关于php - Magento : Category Name instead of category ids in category path.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14118213/

相关文章:

javascript - JS 中声明对象和数组加引号是不是更快?

php - 观察者不保存订单

php - Magento 1.6 : Using MySQL datetime fields with resource models

magento - 如何在 Magento 中使用 getUrl() 引用另一个模块?

javascript - 无需ajax或iframe的回调(纯代码)

PHP SQL 我想在表的1行中显示2组数据

php - 不使用 rand() 从 mysql 数据库返回随机行

excel - 简单的循环,但通过 50 000+ 行

PHP MySQL 查询使用串联赋值变量进行插入

performance - IO分析工具?