2016-11-23 43 views
0

如何清洁和更好下面的“零碎”的PHP代码:如何使这个代码更短,更好

<?php 

error_reporting(E_ALL); 
require_once('app/Mage.php'); 
Mage::init(); 
Mage::getSingleton("core/session", array("name" => "frontend")); 
$productList = array(
    array(), 
    array(), 
    array() 
); 
$count = Mage::getSingleton('checkout/session')->getQuote()->getItemsQty(); 
$cart = Mage::getSingleton('checkout/session')->getQuote()->getAllItems(); 
$name = array(); 
$qty = array(); 
$price = array(); 
for ($i = 0; $i < $count; $i++) { 
    $name[$i] = $cart[$i]->getProduct()->getName(); 
    $qty[$i] = $cart[$i]->getQty(); 
    $price[$i] = $cart[$i]->getProduct()->getPrice(); 
    $productList[$i] = array(
     $name[$i], 
     $qty[$i], 
     $price[$i] 
    ); 
} 
print_r($productList); 

我想知道,如何美化这种frament。可能是我应该使用更短的数组初始化形式,在这种情况下一些标准的PHP函数等。

+5

这属于在http://codereview.stackexchange.com/。 – Fencer04

回答

0

我想这种做法是一个好一点

<?php 
error_reporting(E_ALL); 
require_once("app/Mage.php"); 

function setData($acc, $item) 
{ 
    $acc[] = [ 
    $item->getProduct()->getName(), 
    $item->getQty(), 
    $item->getProduct()->getPrice() 
]; 
return $acc; 
} 

Mage::init(); 
Mage::getSingleton("core/session", ["name" => "frontend"]); 
print_r(array_reduce(Mage::getSingleton("checkout/session")->getQuote() 
->getAllVisibleItems(), "setData", [])); 
1

使用下面的代码

<?php 
error_reporting(E_ALL); 
require_once('app/Mage.php'); 
Mage::init(); 

Mage::getSingleton("core/session", array("name" => "frontend")); 
$productList = array(); 

$quote = Mage::getSingleton('checkout/session')->getQuote(); 

foreach ($quote->getAllItems() as $item) { 
    $productList[]=array($item->getName(),$item->getQty(),$item->getPrice()); 
} 
+0

如果我们想要得到正确的结果,我们将使用_getAllVisibleItems_而不是_getAllItems()_其余的代码是足够好的。 – Twissell

+0

我已将该更正添加到您的变体中。 – Twissell

0
ini_set('display_errors', '1'); 
require_once('app/Mage.php'); 
Mage::app('default'); 
$storeId = 0; 
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load($storeId)); 

$products = Mage::getModel('catalog/product') 
      ->getCollection() 
      ->addAttributeToSelect('*') 

foreach ($products as $product) { 

     print_r($product->getdata()); 

     } 
+0

您的代码不符合我的需求。 因为我想从第三方shell脚本收集上述产品属性。也不是来自magento模块。 – Twissell