I have a data array that totals all the items in the cart for all the products as one number.
I've been trying to figure out a way to get a data array count() all the different totals of all the different items in the cart and have them presented in my data layer comma separated. I hope that makes sense.
if ($order->getId()) {
$items = $order->getAllVisibleItems();
$itemIds = array();
$itemNames = array();
$itemPrices = array();
$itemMargins = array();
$itemTypes = array();
$itemGenders = array();
$itemSports = array();
$itemCategoryIds = array();
$itemCategoryNames = array();
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// Get the parent item - it is NOT included in the quote due to
// customizations made by the OrganicInternet module for simple
// product pricing. So I had to come up with another way to get it.
$options = $item->getProductOptions();
$parent = $item->getProduct();
if (array_key_exists('info_buyRequest', $options)) {
if (array_key_exists('cpid', $options['info_buyRequest'])) {
$parentId = $options['info_buyRequest']['cpid'];
$parent = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('season')
->addAttributeToSelect('gender')
->addAttributeToSelect('sport')
->addAttributeToFilter('entity_id', $parentId)
->getFirstItem();
}
}
$itemIds[] = $item->getSku();
$itemNames[] = $parent->getName();
$itemPrices[] = $item->getBasePrice() ?: 0;
$itemMargins[] = $this->_calculateMargin($parent, null, $item);
$itemTypes[] = $parent->getAttributeText('season');
$itemGenders[] = $parent->getAttributeText('gender');
$itemSports[] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
}
// # Products
$data['u1'] = count($items);
The above will return:
dataLayer = [{"visitorLoginState":"Logged out","visitorType":"NOT LOGGED IN","visitorLifetimeValue":0,"visitorExistingCustomer":"No","u1":2,"u2":["889623392590","889623135517"]
It shows a total of 2 products for the U1 variable and the two sku's for the u2 variable in the data array.
If i have multiple products for the first sku i want it to seperate the quantities. ie.. "u1":1,1,3
Would i use array_sumor some type of multi-dimensional array to acquire my needs?
If i have multiple products for the first sku i want it to seperate
the quantities. ie.. "u1":1,1,3
It is not exactly clear to me is the relationship between sku and product and which variables in your array refer to which. I make the following presumptions:
1) A product is equivalent to one $items element
2) A sku is a unique $itemIds[] value
I use the array key as a simple way to keep track for each unique sku and the value to keep track of the product count for the sku.
if ($order->getId()) {
$items = $order->getAllVisibleItems();
$itemIds = array();
$itemNames = array();
$itemPrices = array();
$itemMargins = array();
$itemTypes = array();
$itemGenders = array();
$itemSports = array();
$itemCategoryIds = array();
$itemCategoryNames = array();
// My addition (UPDATE: fixed to the correct variable name)
$uniqueItemIds = array();
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// Get the parent item - it is NOT included in the quote due to
// customizations made by the OrganicInternet module for simple
// product pricing. So I had to come up with another way to get it.
$options = $item->getProductOptions();
$parent = $item->getProduct();
if (array_key_exists('info_buyRequest', $options)) {
if (array_key_exists('cpid', $options['info_buyRequest'])) {
$parentId = $options['info_buyRequest']['cpid'];
$parent = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('season')
->addAttributeToSelect('gender')
->addAttributeToSelect('sport')
->addAttributeToFilter('entity_id', $parentId)
->getFirstItem();
}
}
// *******************************
// My addition / changes
$sku = $item->getSku();
$itemIds[] = $sku; // I don't use this but keep $itemIds for compatibility
// use the array key to track counts for each sku
if (!isset($uniqueItemIds[$sku])){
$uniqueItemIds[$sku] = 1; // UPDATE: fixed to start at 1 not 0
} else {
$uniqueItemIds[$sku]++;
}
// *******************************
$itemNames[] = $parent->getName();
$itemPrices[] = $item->getBasePrice() ?: 0;
$itemMargins[] = $this->_calculateMargin($parent, null, $item);
$itemTypes[] = $parent->getAttributeText('season');
$itemGenders[] = $parent->getAttributeText('gender');
$itemSports[] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
}
// show # Products
// "u1":1,1,3 NOTE: this should be a string => "u1":"1,1,3"
$data['u1'] = "";
foreach ($uniqueItemIds as $key => $val)
// show unique skus in u2
$data['u2'][] = $key;
// show counts for each sku in u1
if (strlen($data['u1'] == 0)){
$data['u1'] = (string)$value;
} else {
$data['u1'] .= ("," . $value);
}
}
How about something like...
if ($order->getId()) {
.....
.....
.....
/** #var Mage_Sales_Model_Quote_Item $item */
$sku_based_array = array();
foreach ($items as $item) {
......
......
......
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
if (isset($sku_based_array[$item->getSku()])) {
$sku_based_array[$item->getSku()] = $sku_based_array[$item->getSku()]++;
} else {
$sku_based_array[$item->getSku()] = 1;
}
}
// # Products
$data['u1'] = array_values($sku_based_array);
Looking at the code it looks like it will only every return one product as the $parent variable is overwritten to get a first item. I have added a new variable named $itemProductCounts this will be returned to the output $data array as itemProductCounts I suspect this will always equal one.
<?php
if ($order->getId()) {
$items = $order->getAllVisibleItems();
$itemIds = array();
$itemNames = array();
$itemPrices = array();
$itemMargins = array();
$itemTypes = array();
$itemGenders = array();
$itemSports = array();
$itemCategoryIds = array();
$itemCategoryNames = array();
$itemProductCounts = array();
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// Get the parent item - it is NOT included in the quote due to
// customizations made by the OrganicInternet module for simple
// product pricing. So I had to come up with another way to get it.
$options = $item->getProductOptions();
$parent = $item->getProduct();
if (array_key_exists('info_buyRequest', $options)) {
if (array_key_exists('cpid', $options['info_buyRequest'])) {
$parentId = $options['info_buyRequest']['cpid'];
$parent = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('season')
->addAttributeToSelect('gender')
->addAttributeToSelect('sport')
->addAttributeToFilter('entity_id', $parentId)
->getFirstItem();
}
}
$itemIds[] = $item->getSku();
$itemNames[] = $parent->getName();
$itemPrices[] = $item->getBasePrice() ?: 0;
$itemMargins[] = $this->_calculateMargin($parent, null, $item);
$itemTypes[] = $parent->getAttributeText('season');
$itemGenders[] = $parent->getAttributeText('gender');
$itemSports[] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
$itemProductCounts[$item->getSku()] = count($parent);
}
// # Products
$data['u1'] = count($items);
$data['itemProductCounts'] = $itemProductCounts;
With that all being said, the code above should get you close to what you need, you should replace the line $itemProductCounts[$item->getSku()] = count($parent); with the correct array with the product counts for that SKU.
Part of the issue with your data here is that everything in an $item is hidden behind an accessor. Rather than creating multitudes of arrays, I would suggest either creating a new object to house the information, or just modifying the $item directly.
Messing with the object directly has the risk of you accidentally using a variable name that exists in a protected or private scope though, so probably best to use your own, like so.
if ($order->getId()) {
$items = $order->getAllVisibleItems();
// only need one array, no need for all data points to have their own
$myItems = [];
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// basic shell
$myItem = [];
// get $options and $parent
// ...
// build your own data object
$myItem['sku'] = $item->getSku();
$myItem['name'] = $parent->getName();
$myItem['price'] = $item->getBasePrice() ?: 0;
$myItem['margin'] = $this->_calculateMargin($parent, null, $item);
$myItem['type'] = $parent->getAttributeText('season');
$myItem['gender'] = $parent->getAttributeText('gender');
$myItem['sport'] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$myItem['categoryId'] = $categories['id'];
$myItem['categoryName'] = $categories['name'];
$myItems[] = $myItem;
}
// At this point, $myItems is manipulable by all the array_* functions
// number of items e.g. 3
$data['u1'] = count($myItems);
// array of skus e.g. ["889623392590","889623392590","889623135517"]
// note: can use objects for $myItem if on PHP 7
// if you like -> notation better (in the loop)
$skus = array_column($myItems, 'sku');
// array of skus with counts e.g. ["889623392590" => 2, "889623135517" => 1]
$skus_with_counts = array_count_values($skus);
// just the counts (assuming indexes on other arrays must match) e.g. [2, 1]
// note: might be useful if you want to keep the counts as an array in dataLayer
$sku_counts = array_values($skus_with_counts);
// if you want this as a comma-separated list for u1, e.g. "2,1"
// note: will also work if you implode $skus_with_counts
$data['u1'] = implode(',', $sku_counts);
// get a list of unique SKUs (both will work), e.g. ["889623392590","889623135517"]
$data['u2'] = array_unique($skus);
$data['u2'] = array_keys($skus_with_counts);
}
Most of these kinds of PHP functions will work on your other data types as well if you want to do counting and clustering, and as you point out, you can run sum operations over them as well if you wish.
PHP array manipulation references: array_column, array_count_values, array_values, implode, array_unique, array_keys.
As a sidebar, Mage_Sales_Model_Quote_Item does have a getParentItemId() method available and a getQtyOptions method, which returns both the quantity and the product model.
I think you are mixing things.
In a simple sistem you should have:
Order has an array of OrderedItems
Each OrderedItem stores ProductObject and OrderedQuantity
And the ProductObject contains all product data.
So in your example instead of counting SKUs you must have $item->quantity field and you should work with that when you add/delete/edit order contents.
Related
Ok So I'm using wordpress and PHP.
Basicly I get a chosen category from a dropdown menu. I then find it's parents.
But then comes the part where I seem to fail. The output of $parents is a string with the names instead of the ID's.
So I try to get each word from the string into an array.
And loop through them and convert them to their ID number.
I commented out where it doesnt seem to work. What am I doing wrong?
//Create array
$categoriesArray = [];
//Get choice from wp-dropdown
$selected_val = $_POST['cat'];
//Get parents from choice divided by (this seems to output a string)
$parents = get_category_parents( $selected_val, true, ',' );
/*
//Make array from string
$categoriesArray = explode(",",$parents);
for ($i = 0; $i < count($categoriesArray); $i++) {
{
$categoriesArray[$i] = get_cat_ID($categoriesArray[$i]);
}
*/
//the array should look something like this.
//$categoriesArray = ["21","44"];
try this,
function get_level($cat, $level = 0)
{
if ($cat->category_parent == 0) {
return $level;
} else {
$level++;
$cat = get_category($cat->category_parent);
return get_level($cat, $level);
}
}
if (is_category()) {
$cat = get_query_var('cat');
$your_cat = get_category($cat);
echo get_level($your_cat);
}
It had to do with the name of the category. I needed to use the slug instead of the name.
Here is my code that works. I can now make a new post and give it a category with their parents included!
//Create array
$categoriesArray = [];
//Get choice from wp-dropdown
$selected_val = $_POST['cat'];
//Get parents from choice divided by ,
$parents = get_category_parents( $selected_val, true, ',',false);
//Make array from string
$categoriesArray = explode(",",$parents);
for ($i = 0; $i < count($categoriesArray); $i++)
{
$categoriesArray[$i] = get_cat_ID($categoriesArray[$i]);
}
This is my current code, I'm looking for a more efficient way of writing it.
Need something like looping through each variable with a foreach or adding them all to an array somehow, without me having to re-write every variable name.
$formValues = $form_state->getValues();
$relocation = $formValues['relocation'];
$europe = $formValues['europe'];
$twoyears = $formValues['twoyears'];
$realestate = $formValues['realestate'];
$nominated = $formValues['check_nominated_by'];
$nom_comp = $formValues['nom_company'];
$nom_contact = $formValues['nom_contact'];
$nom_email = $formValues['nom_email'];
$contact1 = $formValues['contact1'];
$position1 = $formValues['contact_position1'];
$email1 = $formValues['email1'];
$contact2 = $formValues['contact2'];
$position2 = $formValues['contact2'];
$email2 = $formValues['contact2'];
$contact3 = $formValues['contact3'];
$position3 = $formValues['contact3'];
$email3 = $formValues['contact3'];
tempstore = array();
$tempstore['relocation'] = $relocation;
$tempstore['europe'] = $europe;
$tempstore['twoyears'] = $twoyears;
$tempstore['realestate'] = $realestate;
$tempstore['membertype'] = $membertype;
$tempstore['nominated_by'] = '';
// All other fields need to be in this array too
// But there are a lot of unwanted fields in the $formValues
$_SESSION['sessionName']['formName'] = $tempstore;
Seeing as you know the keys you'd like to keep you can do the following:
<?php
/** The keys you want to keep... **/
$keys_to_keep = [
];
/** Will be used to store values for saving to $_SESSION. **/
$temp_array = [];
/** Loop through the keys/values. **/
foreach ($formValues as $key => $value) {
/** The correct key i.e. the key you'd like to save. **/
if (in_array($key, $keys_to_keep)) {
/** What you wish to do... **/
$temp_array[$key] = $value;
}
}
$_SESSION['sessionName']['formName'] = $temp_array;
?>
What is happening is that you are looping through your $formValues and getting both the keys and values of each pair in the array.
Then an check is being done against your $keys_to_keep to see if the current element is the one you wish to keep, if it is then you save it in to $temp_array.
Reading Material
foreach
in_array
You can use variable variables and a foreach.
Foreach($formValues as $key => $var){
$$key = $var;
}
Echo $relocation ."\n" . $europe;
https://3v4l.org/QeLjp
Edit I see now that your array variable keys are not always the same as the variable name you want.
In that case you can't use the method above.
In that case you need to use list() = array.
List($relocation, $europe) = $formValues;
// The list variables have to be in correct order I just took the first two for demo purpose.
I have a php object (book) with 3 properties: name, category, description
I then have a list of these book objects in an array.
I want to create a new associative array for these objects grouped by category.
Say I have 4 book objects in an array called $books
name category description
==================================
book1 cat1 this is book 1
book2 cat1 this is book 2
book3 cat2 this is book 3
book4 cat3 this is book 4
how can I create an associative array called $categories
$categories['cat1'] = array(book1, book2)
$categories['cat2'] = array(book2)
$categories['cat3'] = array(book3)
where book? is the book object and not the word
Like this:
foreach($books as $book)
{
$categories[$book->category][] = $book;
}
Simply loop the array of objects into a new array with the key being the category:
$newArray = array();
foreach($array as $entity)
{
if(!isset($newArray[$entity->category]))
{
$newArray[$entity->category] = array();
}
$newArray[$entity->category][] = $entity;
}
Is this what you was looking for ?
Explanation of the code:
/*
* Create a new blank array, to store the organized data in.
*/
$newArray = array();
/*
* Start looping your original dataset
*/
foreach($array as $entity)
{
/*
* If the key in the new array does not exists, set it to a blank array.
*/
if(!isset($newArray[$entity->category]))
{
$newArray[$entity->category] = array();
}
/*
* Add a new item to the array, making shore it falls into the correct category / key
*/
$newArray[$entity->category][] = $entity;
}
You can do it with ouzo goodies:
$categories = Arrays::groupBy($books, Functions::extractField('category'));
See: http://ouzo.readthedocs.org/en/latest/utils/arrays.html#groupby
$categories = array();
for ($i = 0; $i < count($books); $i++){
if (isset($categories[$books[$i]->category]) == false)
$categories[$books[$i]->category] = array();
$categories[$books[$i]->category][] = $books[$i]
}
cheers
Try this:
$categories = array();
foreach ($books as $book){
if (!array_key_exists($book->category , $categories))
$categories[$book->category] = array();
$categories[$book->category][] = $book;
}
This should works:
$categories = array();
foreach ($books as $book) {
$categories[$book['category']][] = $book;
}
I had a similar problem, but a bit more complicated with wordpress and metavalues/metakeys (where $results was an array of associative arrays fetched from a $wpdb->get_results() query.
This was my solution adapted to your problem:
$categories = array();
foreach ($results as $row) {
$id = $row['category'];
$description = $row['category'];
$name = $row['name']
if (!isset($categories[$id])) {
$categories[$id] = array();
}
$categories[$id] = array_merge($categories[$id], 'description'=>$description , 'name'=>$name);
}
Then you can run another for loop to get each array from the categories array:
foreach ($categories as $category) {
var_dump($category);
}
If you want to group objects by getting key from specific method with or without additional arguments, you can use this library method:
Arr::groupObjects(array $objects, string $method, ...$args): array
i am building a shopping cart and cant figure out how to store something like this into a session.
[product_id1] = quantity;
[product_id1] = size
[product_id1] = color;
[product_id2] = quantity;
[product_id2] = size;
[product_id2] = color;
...
etc
so when a user select the quantity of a product then selects its color then selects to add to a cart i want the items selected to be added into a session and each item added to the cart , its attributes selected to be added into a session. how would i do this?
many many thanks.
$_SESSION['productid1']['quantity'] = 15;
$_SESSION['productid1']['size'] = 30;
$_SESSION['productid1']['color'] = 'red';
$_SESSION['productid2']['quantity'] = 35;
$_SESSION['productid2']['size'] = 2;
$_SESSION['productid2']['color'] = 'blue';
Don't forget to put session_start() at the beginning of every page to carry the sessions through the pages.
$item[$catalog_number]['quantity'] = 1;
$item[$catalog_number]['size'] = 'XL';
$item[$catalog_number]['color'] = 'yellow';
$_SESSION['cart'][] = $item;
unset($item);
Repeat for each item you are adding. Alternatively you could do:
$item['catalog_number'] = 'ABC-123';
$item['quantity'] = 1;
$item['size'] = 'XL';
$item['color'] = 'yellow';
$_SESSION['cart'][] = $item;
unset($item);
Both will work, just make sure you are consistent. Use only one or the other.
You should create an array in session array for your products:
$_SESSION['products'] = Array();
then you can put products there like this:
$product = Array();
$product['quantity'] = 6;
$product['size'] = 'XXL';
$product['color'] = 'blue';
$_SESSION['products'][] = $product;
$product = Array();
$product['quantity'] = 2;
$product['size'] = 'XL';
$product['color'] = 'blue';
$_SESSION['products'][] = $product;
this will give you numbered array, if you want an associative array, you will just put identifier into []:
$_SESSION['products']['productID'] = $product;
Does anyone know how I can get a list of products belonging to a specific category from within a view file in Magento?
You can use magento object to filter.
Example:
$categoryId = 123; // a category id that you can get from admin
$category = Mage::getModel('catalog/category')->load($categoryId);
$products = Mage::getModel('catalog/product')
->getCollection()
->addCategoryFilter($category)
->load();
print_r($products);
It all depends on which view you're in. ;-)
First off, I hope you stayed within your template set (default in my example).
Use this as an example:
<?php
$_cat = $this->getCurrentCategory();
$_parent = $_cat->getParentCategory();
$_categories = $_parent->getChildren();
/* #var $category Mage_Catalog_Model_Category */
$collection = Mage::getModel('catalog/category')->getCollection();
/* #var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
$collection->addAttributeToSelect('url_key')
->addAttributeToSelect('name')
->addAttributeToSelect('is_anchor')
->addAttributeToFilter('is_active', 1)
->addIdFilter($_categories)
->setOrder('position', 'ASC')
->joinUrlRewrite()
->load();
$productCollection = Mage::getResourceModel('catalog/product_collection');
$layer = Mage::getSingleton('catalog/layer');
$layer->prepareProductCollection($productCollection);
$productCollection->addCountToCategories($collection);
// $productCollection should be ready here ;-)
?>
I'm using the above code to display sister categories in my template - it's not ideal but it works.
It's sort of a hack because I did not yet have time to learn all the layout XML madness. Otherwise if you use the XMLs you need to keep in mind - it all depends on where you are at. Where means the template file and essentially also the layout (in terms of app/design/frontend/default/default/layout/*).
I know it's not much, but I hope it helps to get you started.
Here is the code to get products from any particular category. You can use this in view file as well.
// if you want to display products from current category
$category = Mage::registry('current_category');
// if you want to display products from any specific category
$categoryId = 10;
$category = Mage::getModel('catalog/category')->load($categoryId);
$productCollection = Mage::getResourceModel('catalog/product_collection')
->addCategoryFilter($category);
// printing products name
foreach ($productCollection as $product) {
echo $product->getName();
echo "<br />";
}
<?php
$c_id = 2;
$category = new Mage_Catalog_Model_Category();
$category->load($c_id);
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
foreach ($collection as $_product) { ?>
<?php echo $_product->getName(); ?>
<?php } ?>
I pretty much needed the same. Here is how I have done it:
$prod_whole = array();
if(!empty($_menu)) //$_menu = array of Categories with some basic info
foreach($_menu as $v)
{
if($v['name']=='HOME')
continue;
$cat_id = $v['id'];
#/ Setup Products
$category = Mage::getModel('catalog/category')->load($cat_id);
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*') // select all attributes
->addCategoryFilter($category)
->setPageSize(8) // limit number of results returned
->setCurPage(0)
->load()
;
$prod_collection = array();
foreach ($collection as $product)
{
$prod_collection_1 = array();
#/ Basic Info
$prod_collection_1['id'] = $product->getId();
$prod_collection_1['name'] = $product->getName();
$prod_collection_1['price'] = (float) $product->getPrice();
//$prod_collection_1['desc'] = $product->getDescription();
//$prod_collection_1['short'] = $product->getShortDescription();
$prod_collection_1['type'] = $product->getTypeId();
$prod_collection_1['status'] = $product->getStatus();
$prod_collection_1['special_price'] = $product->getSpecialPrice();
$prod_collection_1['direct_url'] = $product->getProductUrl();
#/ getCategoryIds(); returns an array of category IDs associated with the product
foreach ($product->getCategoryIds() as $category_id)
{
$category = Mage::getModel('catalog/category')->load($category_id);
$prod_collection_1['parent_category'] = $category->getParentCategory()->getName();
$prod_collection_1['category'] = $category->getName();
//$prod_collection_1['category_idx'] = preg_replace('/[\s\'\"]/i', '_', strtolower(trim($prod_collection_1['category'])));
$prod_collection_1['category_id'] = $category->getId();
}
#/gets the image url of the product
$prod_collection_1['img'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();
$prod_collection[] = $prod_collection_1;
}//end foreach.....
$prod_whole[$cat_id] = $prod_collection;
}//end foreach categories.......
//var_dump('<pre>', $prod_whole);
Hope this helps.
<?php
$category_id = 10; // if you know static category then enter number
$catagory_model = Mage::getModel('catalog/category')->load($category_id); //where $category_id is the id of the category
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addCategoryFilter($catagory_model); //category filter
$collection->addAttributeToFilter('status',1); //only enabled product
$collection->addAttributeToSelect(array('name','url','small_image')); //add product attribute to be fetched
//$collection->getSelect()->order('rand()'); //uncomment to get products in random order
$collection->addStoreFilter();
if(!empty($collection))
{
foreach ($collection as $_product):
echo $_product->getName(); //get product name
endforeach;
}else
{
echo 'No products exists';
}
?>
You should always avoid putting code like this into a view, it's very bad practice.
You can also run into issues as views can be cached, leading to unexpected behaviour.
you should override the block you are using, placing code there. you can then call any new methods inside your view files.
for example, you could copy Mage_Catalog_Block_Product_List
from: app/code/core/Catalog/Block/Product/List.php
to: app/code/local/Catalog/Block/Product/List.php
you could then add a new method, possibly using some of the code mentioned in the above posts.
your new method would then be available inside your view file (list.phtml or any view using this block)
Here is a code to export all product with it's category into csv
<?php
set_time_limit(0);
ini_set("memory_limit",-1);
ini_set('max_execution_time','1800000000');
require_once '../app/Mage.php';
Mage::app();
$category = Mage::getModel('catalog/category');
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
$fp = fopen('category-product-export.csv', 'w');
$field = array('Product SKU','Category Name');
fputcsv($fp, $field);
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->load();
foreach ($_productCollection as $_product){
$cats = $_product->getCategoryIds();
$cnt = 0;
$catName = '';
foreach($cats as $id) {
$category->load($id);
$root = 'Root Catalog';
$isRoot = strtolower($root);
$categoryName = strtolower($category->getName());
if($categoryName == $isRoot){
continue;
}
$categories[$id]['name'] = $category->getName();
$categories[$id]['path'] = $category->getPath();
$path = explode('/', $categories[$id]['path']);
$len = count($path);
$string = '';
if($id > 2){
foreach ($path as $k=>$pathId)
{
$separator = '';
if($pathId > 2){
$category->load($pathId);
if($k != $len-1){ $separator = ' || ';}
$string.= $category->getName() . $separator;
}
}
if($cnt > 0) {
$catName.= ','.$string;
} else {
$catName = $string;
}
$cnt++;
}
}
//echo $catName;
$field = array($_product->getSku(),$catName);
fputcsv($fp, $field);
}
?>
Download