2016-11-08 34 views
17

我有一個數據數組,將所有產品中的所有商品作爲一個數字進行彙總。如何將產品數量存儲在一個陣列中

我一直在想辦法獲得一個數據數組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); 

上面將返回:

數據層= [{ 「visitorLoginState」: 「註銷」, 「visitorType」: 「沒有登錄」, 「visitorLifetimeValue」:0 「visitorExistingCustomer」: 「否」,「u1」:2,「u2」:[「889623392590」,「889623135517」]

它顯示了總共2個產品的U1變量和兩個sku的u2變量的數據陣列。

如果我有多個產品的第一個sku我希望它分開的數量。即.. "u1":1,1,3

我會使用array_sum或某種類型的多維數組來獲得我的需求嗎?

+0

是否有必要將所有這些數據存儲在一個巨大的多嵌套數組中?充其量,這很難遵循。如果將其分解到更原子級別,您可能會有更輕鬆的時間。 – Matt1776

+0

@ Matt1776,我願意提供建議或任何其他方式獲取數據。 – thismethod

+4

我提出了一些重構,我不知道你的問題或數據是否足以提出這樣的建議,除了你可能想要考慮使用多個數組或哈希/地圖/字典對象或者只是嵌套較少的數據。當它嵌套在一個對象內時,跟蹤數據變得非常困難。重新考慮如何存儲和檢索數據,解決方案將變得更加清晰。 – Matt1776

回答

6

如果我有多個產品的第一個SKU,我希望它分開 的數量。即..「U1」:1,1,3

這是不完全清楚,我是你的陣列指的SKU和產品以及變量之間的關係。我提出以下推定: 1)一種product等效於一個$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); 
     }    
    } 
-1

我想你是混合的東西。

在一個簡單的SISTEM你應該有:

  • 訂單OrderedItems

  • 陣列,每個OrderedItem店ProductObject和OrderedQuantity

  • 而且ProductObject包含所有產品數據。

所以,在你的榜樣,而不是計數的SKU,你必須有$用品 - >量場,你應該與該工作的時候添加/刪除/修改訂單內容。

+1

OP正在使用現有系統(Magento),無法控制設計。他也在談論彼此變化的產品,但具有相同的SKU,因此您提及的數量方法不適用。在這個迴應中也沒有什麼實際上有助於回答OP。 – Leith

+0

我稍微不同意你的看法。 – GodlyHedgehog

+1

OP實際上會填充來自作爲產品模型的父對象提供的代碼中的所有數據。 +即使你的評論引入數量會使計算更容易。 存儲任何東西的副本總是一個壞主意。這就是OP的實際做法 – GodlyHedgehog

1

如何像...在這裏你的數據的問題

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); 
1

部分原因是,在$item一切都隱藏在背後的訪問。我建議不是創建大量數組,而是建議創建一個新對象來存放信息,或者直接修改$item

與物體直接混淆可能會導致意外使用存在於protectedprivate範圍內的變量名稱,因此可能最好使用自己的,如上所述。

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數組操作的引用:array_columnarray_count_valuesarray_valuesimplodearray_uniquearray_keys

作爲一個側邊欄,Mage_Sales_Model_Quote_Item確實有getParentItemId()方法可用和getQtyOptions方法,該方法返回數量和產品模型。

1

看看代碼,它看起來像只會返回一個產品,因爲$parent變量被覆蓋以獲得第一個項目。我添加了一個名爲$itemProductCounts的新變量,這將返回到輸出$data數組作爲itemProductCounts我懷疑這將永遠等於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; 

有了這一切都這樣說,上面的代碼應該讓你接近你需要什麼,你應該與該SKU的產品計數正確的陣列更換線$itemProductCounts[$item->getSku()] = count($parent);

相關問題