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.
我一直试图找到一种方法来获取数据数组count()购物车中所有不同项目的所有不同总数,并将它们以我的数据层逗号分隔。我希望这是有道理的。
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.
它显示了U1变量的总共2个产品和数据数组中u2变量的两个sku。
If i have multiple products for the first sku i want it to seperate the quantities. ie.. "u1":1,1,3
如果我有第一个sku的多个产品,我希望它分开数量。即..“u1”:1,1,3
Would i use array_sum
or some type of multi-dimensional array to acquire my needs?
我会使用array_sumor某种类型的多维数组来获取我的需求吗?
5 个解决方案
#1
6
If i have multiple products for the first sku i want it to seperate the quantities. ie.. "u1":1,1,3
如果我有第一个sku的多个产品,我希望它分开数量。即..“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
我不完全清楚sku和产品之间的关系以及数组中哪些变量引用哪些变量。我做出以下假设:1)产品相当于一个$ items元素2)sku是唯一的$ itemIds []值
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.
我使用数组键作为跟踪每个唯一sku的简单方法,并使用值来跟踪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);
}
}
#2
1
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);
#3
1
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.
查看代码看起来它只会返回一个产品,因为$ parent变量会被覆盖以获得第一个项目。我添加了一个名为$ itemProductCounts的新变量,这将作为itemProductCounts返回到输出$ data数组我怀疑它总是等于1。
<?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.
尽管如此,上面的代码应该让你接近你所需要的,你应该替换$ itemProductCounts [$ item-> getSku()] = count($ parent);使用正确的数组,包含该SKU的产品数量。
#4
1
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.
此处数据的部分问题是$ item中的所有内容都隐藏在访问者后面。我建议创建一个新对象来存放信息,或者直接修改$ item,而不是创建大量数组。
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函数也适用于你的其他数据类型,正如你所指出的,你可以根据需要对它们运行求和运算。
PHP array manipulation references: array_column
, array_count_values
, array_values
, implode
, array_unique
, array_keys
.
PHP数组操作引用: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.
作为侧边栏,Mage_Sales_Model_Quote_Item确实有一个getParentItemId()方法和一个getQtyOptions方法,它返回数量和产品模型。
#5
-1
I think you are mixing things.
我觉得你在混合东西。
In a simple sistem you should have:
在一个简单的系统你应该有:
-
Order has an array of OrderedItems
Order有一个OrderedItems数组
-
Each OrderedItem stores ProductObject and OrderedQuantity
每个OrderedItem都存储ProductObject和OrderedQuantity
-
And the ProductObject contains all product data.
ProductObject包含所有产品数据。
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.
因此,在您的示例中,您必须拥有$ item-> quantity字段而不是计算SKU,并且在添加/删除/编辑订单内容时应该使用该字段。
#1
6
If i have multiple products for the first sku i want it to seperate the quantities. ie.. "u1":1,1,3
如果我有第一个sku的多个产品,我希望它分开数量。即..“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
我不完全清楚sku和产品之间的关系以及数组中哪些变量引用哪些变量。我做出以下假设:1)产品相当于一个$ items元素2)sku是唯一的$ itemIds []值
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.
我使用数组键作为跟踪每个唯一sku的简单方法,并使用值来跟踪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);
}
}
#2
1
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);
#3
1
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.
查看代码看起来它只会返回一个产品,因为$ parent变量会被覆盖以获得第一个项目。我添加了一个名为$ itemProductCounts的新变量,这将作为itemProductCounts返回到输出$ data数组我怀疑它总是等于1。
<?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.
尽管如此,上面的代码应该让你接近你所需要的,你应该替换$ itemProductCounts [$ item-> getSku()] = count($ parent);使用正确的数组,包含该SKU的产品数量。
#4
1
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.
此处数据的部分问题是$ item中的所有内容都隐藏在访问者后面。我建议创建一个新对象来存放信息,或者直接修改$ item,而不是创建大量数组。
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函数也适用于你的其他数据类型,正如你所指出的,你可以根据需要对它们运行求和运算。
PHP array manipulation references: array_column
, array_count_values
, array_values
, implode
, array_unique
, array_keys
.
PHP数组操作引用: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.
作为侧边栏,Mage_Sales_Model_Quote_Item确实有一个getParentItemId()方法和一个getQtyOptions方法,它返回数量和产品模型。
#5
-1
I think you are mixing things.
我觉得你在混合东西。
In a simple sistem you should have:
在一个简单的系统你应该有:
-
Order has an array of OrderedItems
Order有一个OrderedItems数组
-
Each OrderedItem stores ProductObject and OrderedQuantity
每个OrderedItem都存储ProductObject和OrderedQuantity
-
And the ProductObject contains all product data.
ProductObject包含所有产品数据。
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.
因此,在您的示例中,您必须拥有$ item-> quantity字段而不是计算SKU,并且在添加/删除/编辑订单内容时应该使用该字段。