2013-06-06 22 views
1

我需要收集給定產品的所有可用屬性,然後使用它們創建多維數組。希望你可以創建一個具有兩個以上維度的多維數組?結果數組的聲明應該是這樣的:Magento將屬性收集爲多維數組鍵

$simpleArray[$child->getVendor()][$child->getColor()]=$child->getPrice(); 

首先,我收集的所有屬性,然後將其添加到字符串,我可以調用每一個後來:

$_product = $this->getProduct(); 
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes()); 


//Gather all attribute labels for given product 

    foreach($_attributes as $_attribute){ 
      $attributeString .= '[$child -> get' . ucfirst($_attribute->getLabel()) . '()]'; 
    } 

然後我試圖將該字符串附加到數組以聲明它:

foreach($childProducts as $child) { //cycle through simple products to find applicable 
    //CAITLIN you are going to need way to search for other attributes, GET list of attributes 
    $simpleArray. $attributeString =$child->getPrice(); 
}    
Mage::log('The attributeString is '. $simpleArray. $attributeString, null, 'caitlin.log'); //This is logging as "The attributeString is Array74" 

有什麼建議嗎?

+0

你試圖讓你的價格圖出magento? –

+0

這是我對它的理解,我在回答中做了一些非常顯着的改變,因爲使用for循環在嘗試向後「生成未知深度的多級數組」時變得非常簡單。 –

回答

0

編寫代碼時,您將需要使用遞歸來完成您請求的內容,而無需知道屬性名稱。

這將循環並提供基於可配置屬性的多維數組中的所有子產品價格。它假定$ _product是當前的產品。

$attrs = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product); 
$map = array(); 
foreach($attrs as $attr) { 
    $map[] = $attr['attribute_code']; 
} 
$childPricing = array(); 
$childProducts = $_product->getTypeInstance()->getUsedProducts(); 
foreach($childProducts as $_child) { 
    // not all of the child's attributes are accessible, unless we properly load the full product 
    $_child = Mage::getModel('catalog/product')->load($_child->getId()); 
    $topLevel = array($child->getData($map[sizeof($map)]) => $_child->getPrice()); 
    array_pop($map); 
    $childProducts = array_merge($childProducts,$this->workThroughAttrMap($map,$_child,$topLevel)); 
} 
//print_r childProducts to test, later do whatever you were originally planning with it. 

在同一個控制器包括這樣的:

protected function workThroughAttrMap(&$map,$child,$topLevel) { 
    $topLevel = array($child->getData($map[sizeof($map)]) => $topLevel); 
    array_pop($map); 
    if(sizeof($map) > 0) return workThroughAttrMap($map,$child,$topLevel); 
    else return $topLevel; 
} 

我沒有測試此代碼,所以可能會有一些小錯誤。

有幾件事情可以使代碼更清潔一些,比如將第一個$ topLevel代碼移動到函數中,使其成爲一個可選參數,並在不存在時用價格初始化它。我也沒有包括任何錯誤檢查(如果產品不可配置,兒童產品沒有設定價格等)。

+0

沒關係,它錯過了一個「)」。不要以爲我能夠將箭頭放在那裏,但我實際上是在模板文件中這樣做的貧民窟方式。 – CaitlinHavener

+0

也是=>應該是 - >? – CaitlinHavener

+0

嘿,我只是試圖調試一個小時。還是很困惑。任何方式來工作我已經做了什麼? – CaitlinHavener