Php 如何在阵列中存储产品数量
我有一个数据数组,它将购物车中所有产品的所有项目合计为一个数字 我一直在试图找到一种方法来获取数据数组count(),即购物车中所有不同项目的所有不同总计,并将它们以逗号分隔显示在我的数据层中。我希望这是有道理的Php 如何在阵列中存储产品数量,php,arrays,count,Php,Arrays,Count,我有一个数据数组,它将购物车中所有产品的所有项目合计为一个数字 我一直在试图找到一种方法来获取数据数组count(),即购物车中所有不同项目的所有不同总计,并将它们以逗号分隔显示在我的数据层中。我希望这是有道理的 if ($order->getId()) { $items = $order->getAllVisibleItems(); $itemIds = array(); $itemNames = array(); $itemPrices = arr
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);
以上内容将返回:
数据层=[{“visitorLoginState”:“注销”,“visitorType”:“未登录”,“VisitorLifeTime值”:0,“visitorExistingCustomer”:“否”,“u1”:2,“u2”:[“889623392590”,“889623135517”]
它显示了数据数组中U1变量的总共2个产品和u2变量的两个sku
如果我的第一个sku有多个产品,我希望它将数量分开。即..“u1”:1,1,3
我会使用数组\u sum
还是某种多维数组来满足我的需求
如果我有多个产品的第一个sku,我希望它分开
数量,即“u1”:1,1,3
我不太清楚sku和产品之间的关系,以及数组中的哪些变量引用了哪些变量。我做出以下假设:
1) 产品
相当于一个$items
元素
2) sku
是唯一的$itemIds[]
值
我使用数组键作为跟踪每个唯一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);
}
}
我认为你在混淆视听 在一个简单的系统中,您应该具有:
- Order有一个OrderedItems数组
- 每个OrderedItem存储ProductObject和OrderedQuantity
- ProductObject包含所有产品数据
因此,在您的示例中,您必须有$item->quantity字段,而不是计算SKU,并且在添加/删除/编辑订单内容时应该使用该字段。类似于
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);
此处数据的部分问题在于,
$item
中的所有内容都隐藏在访问器后面。与其创建大量数组,我建议创建一个新对象来存放信息,或者直接修改$item
直接使用对象可能会有意外使用受保护
或私有
范围中存在的变量名的风险,因此最好使用自己的变量名,就像这样
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);
}
如果您想进行计数和聚类,那么这些类型的PHP函数中的大多数也可以用于其他数据类型,并且正如您所指出的,如果您愿意,也可以对它们运行求和操作
PHP数组操作引用:、、
作为一个侧栏,
Mage\u Sales\u Model\u Quote\u Item
确实有一个可用的方法和一个返回数量和产品型号的方法。查看代码,它似乎只会每次返回一个产品,因为$parent
变量被覆盖以获取第一个项目。我添加了一个名为的新变量$itemProductCounts
这将作为itemProductCounts
返回到输出$data
数组。我怀疑这将始终等于一
<?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;
是否有必要将所有这些数据存储在一个巨大的多嵌套数组中?这最多很难理解。如果您将其分解为更原子的级别,您可能会更轻松。@Matt1776,我愿意接受建议或任何其他获取数据的方法。我建议进行一些重构,我不知道您的问题或您的数据尽管您可能需要考虑使用多个数组,或者哈希/映射/字典对象,或者简单地嵌套更少的数据。但是,当嵌套在一个对象内时,跟踪数据变得非常困难。重新考虑如何存储和检索数据,并且解决方案将变得更加清晰。o您。您能在代码中的任何地方描述一下:我如何知道某些sku是否有多个产品?什么变量或函数说明一个sku中没有不同类别的产品?您能详细说明吗?OP正在使用现有系统(Magento)并且无法控制设计。他也在谈论彼此不同的产品,但具有相同的SKU,因此您提到的数量方法不适用。此外,此响应中的任何内容实际上都无助于回答OP。我稍微不同意您的看法。OP实际上填充了父对象(t)提供的代码中的所有数据产品模型。+即使你这么说,引入数量也会使计算更容易。存储任何东西的副本总是一个坏主意。而这正是OP doesOP从QuoteItem模型中所做的工作,该模型可以提供数量(我修改了我的答案,以提供具体的参考)产品模型,虽然取决于系统实现,但他可能无法使用它来区分JSON数据层对象所需的方式。问题也不是“如何为此设计系统”,而是“如何使用PHP获取所需信息”。使用副本也不一定是坏的在你所做的事情上,有时使用副本是很重要的;没有理由的笼统概括是毫无意义的。