2016-11-08 15 views
17

Tôi có một mảng dữ liệu tổng tất cả các mục trong giỏ hàng cho tất cả các sản phẩm dưới dạng một số.Cách lưu trữ số lượng sản phẩm trong một mảng

Tôi đã cố gắng tìm ra cách để lấy tổng số dữ liệu() tất cả các tổng khác nhau của tất cả các mục khác nhau trong giỏ hàng và chúng được trình bày trong lớp dữ liệu được phân cách bằng dấu phẩy. Tôi hy vọng điều đó đúng.

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

trên sẽ trở lại:

dataLayer = [{ "visitorLoginState": "Đã lưu IP ngoài", "visitorType": "không đăng nhập", "visitorLifetimeValue": 0, "visitorExistingCustomer": "Không", "u1": 2, "u2": ["889623392590", "889623135517"]

Nó hiển thị tổng cộng 2 sản phẩm cho biến U1 và hai sku cho biến u2 trong dữ liệu mảng.

Nếu tôi có nhiều sản phẩm cho sku đầu tiên tôi muốn nó tách riêng số lượng. tức là .. "u1":1,1,3

Tôi có sử dụng array_sum hoặc một số loại mảng đa chiều để có được nhu cầu của mình không?

+0

Có cần phải lưu trữ tất cả dữ liệu này trong một mảng đa lồng nhau khổng lồ không? Đây là khó khăn để làm theo, tốt nhất. Bạn có thể có một thời gian dễ dàng hơn nếu bạn đã phá vỡ điều này xuống một cấp độ nguyên tử hơn. – Matt1776

+0

@ Matt1776, tôi đang mở cho các đề xuất hoặc bất kỳ phương tiện nào khác để nhận dữ liệu. – thismethod

+4

Tôi gợi ý một chút về refactor, tôi không biết vấn đề của bạn hay dữ liệu của bạn đủ tốt để đưa ra gợi ý như vậy, ngoài ra bạn có thể muốn xem xét sử dụng nhiều hơn một mảng, hoặc một đối tượng hash/map/dictionary hoặc đơn giản là lồng ghép ít dữ liệu hơn. Nó trở nên rất khó khăn để theo dõi dữ liệu khi nó được lồng trong một đối tượng. Hãy suy nghĩ lại cách bạn muốn lưu trữ và truy xuất dữ liệu và giải pháp sẽ trở nên rõ ràng hơn cho bạn. – Matt1776

Trả lời

6

Nếu tôi có nhiều sản phẩm cho sku đầu tiên tôi muốn nó tách riêng số lượng. tức là .. "u1": 1,1,3

Nó không chính xác rõ ràng với tôi là mối quan hệ giữa sku và sản phẩm và biến nào trong mảng của bạn tham chiếu đến. Tôi làm cho giả định sau: 1) Một product là tương đương với một $items yếu tố 2) Một sku là một $itemIds[] giá trị duy nhất

tôi sử dụng phím mảng như là một cách đơn giản để theo dõi cho mỗi sku độc đáo và giá trị để theo dõi số lượng sản phẩm cho 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

Tôi nghĩ bạn đang pha trộn mọi thứ.

Trong một sistem đơn giản bạn nên có:

  • tự có một loạt các OrderedItems

  • Mỗi cửa hàng OrderedItem ProductObject và OrderedQuantity

  • Và ProductObject chứa tất cả các dữ liệu sản phẩm.

Vì vậy, trong ví dụ của bạn thay vì đếm SKU, bạn phải có $ item-> quantity field và bạn nên làm việc với điều đó khi bạn thêm/xóa/chỉnh sửa nội dung đơn đặt hàng.

+1

OP hoạt động với hệ thống hiện có (Magento) và không thể điều khiển thiết kế. Anh ấy cũng nói về các sản phẩm là các biến thể của nhau, nhưng có cùng SKU, vì vậy phương pháp số lượng bạn đề cập không áp dụng. Cũng không có gì trong phản ứng này thực sự giúp trả lời OP. – Leith

+0

Tôi hơi không đồng ý với bạn. – GodlyHedgehog

+1

OP thực sự lấp đầy tất cả dữ liệu trong mã được cung cấp từ đối tượng mẹ là mô hình sản phẩm. + ngay cả với nhận xét của bạn, việc giới thiệu số lượng sẽ làm cho việc tính toán dễ dàng hơn. Và lưu trữ bản sao của bất cứ điều gì luôn luôn là một ý tưởng tồi. Và đó là những gì OP thực sự làm – GodlyHedgehog

1

Làm thế nào về một cái gì đó giống như ...

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

Một phần của vấn đề với dữ liệu của bạn ở đây là tất cả mọi thứ trong một $item được ẩn đằng sau một accessor.Thay vì tạo ra vô số mảng, tôi sẽ đề nghị tạo một đối tượng mới để chứa thông tin hoặc chỉ sửa đổi trực tiếp $item.

Lẫn lộn với đối tượng trực tiếp có nguy cơ bạn vô tình sử dụng tên biến tồn tại trong phạm vi protected hoặc private, vì vậy có lẽ tốt nhất nên sử dụng riêng của bạn, như vậy.

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

Hầu hết các loại chức năng PHP sẽ làm việc trên các kiểu dữ liệu khác của bạn cũng như nếu bạn muốn làm đếm và clustering, và như bạn chỉ ra, bạn có thể chạy các hoạt động tổng hợp lên chúng cũng như nếu bạn muốn .

PHP tham khảo mảng thao tác: array_column, array_count_values, array_values, implode, array_unique, array_keys.

Là thanh bên, Mage_Sales_Model_Quote_Item hiện có phương thức getParentItemId() và phương thức getQtyOptions, trả về cả số lượng và mô hình sản phẩm.

1

Nhìn vào mã có vẻ như nó sẽ chỉ trả về một sản phẩm khi biến số $parent bị ghi đè để lấy mục đầu tiên. Tôi đã thêm một biến mới có tên là $itemProductCounts điều này sẽ được trả về đầu ra $data mảng là itemProductCounts Tôi nghi ngờ điều này sẽ luôn bằng một.

<?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; 

Với rằng tất cả đang được nói, các mã trên sẽ giúp bạn gần với những gì bạn cần, bạn nên thay thế dòng $itemProductCounts[$item->getSku()] = count($parent); với mảng đúng với số lượng sản phẩm mà SKU.

Các vấn đề liên quan