我的数据库中有一个名为 test_category 的 Costum 表,其中包含列:
entity_id
(主键和自动增量)、category_id
和 category_name
我有存储在数组中的类别数据,我想通过magento中的 Controller 将其插入数据库,有什么方法可以像这样在数组中插入数据
Array
(
[category_id] => Array
(
[0] => 13361
[1] => 13697
[2] => 13755
[3] => 13760
)
[category_name] => Array
(
[0] => Baby & Toddler
[1] => Baby & Toddler - Baby Gear
[2] => Baby & Toddler - Baby Gear - Backpacks & Carriers
[3] => Baby & Toddler - Baby Gear - Backpacks & Carriers - Accessories
)
)
最佳答案
<?php
require_once dirname(__FILE__) . '/app/Mage.php';
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
// Your data array
$catarr = array (
'category_id' => array (13361,13697,13755,13760),
'category_name' => array('Baby & Toddler','Baby & Toddler - Baby Gear','Baby & Toddler - Baby Gear - Backpacks & Carriers','Baby & Toddler - Baby Gear - Backpacks & Carriers - Accessories')
);
$combineArr = array_combine($catarr['category_id'],$catarr['category_name']);
echo '<pre>';
print_r($catarr);
print_r($combineArr);
echo '</pre>';
// set your parent category
$parentId = '2';
foreach($combineArr as $combineArrKey => $combineArrVal) {
try{
$category = Mage::getModel('catalog/category');
$category->setName($combineArrVal);
//$category->setId($combineArrKey);
//$category->setUrlKey('your-cat-url-key');
$category->setIsActive(1);
$category->setDisplayMode('PRODUCTS');
$category->setIsAnchor(1); //for active anchor
$category->setStoreId(Mage::app()->getStore()->getId());
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
$category->save();
} catch(Exception $e) {
echo $e->getMessage();
echo '<br />';
}
}
?>
您可以将此文件放在根文件夹中并运行。如果您想在 Controller 中使用它,只需删除顶部的 2 行代码即可。
如果您想要相同的类别 ID,则使用
$category->setId($combineArrKey);
关于php - 如何通过Magento中的 Controller 将数组中的多个数据插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41275828/