【问题标题】:Get two data with one loop一次循环获取两个数据
【发布时间】:2017-07-19 14:03:55
【问题描述】:

我从这样的控制器中的某种形式获得两个参数:

$productIds = $this->getRequest()->getParam('productId');
$productQtys = $this->getRequest()->getParam('qty');

结果:

[productId] => Array(
               [0] => 106
               [1] => 107
               [2] => 108
               [3] => 109
               )    
[qty] => Array(
               [0] => 4
               [1] => 3
               [2] => 2
               [3] => 1
              )

好的,现在我想进入 每个循环 productIdqty

我测试了它适用于产品,但我无法获得数量:

foreach($productIds as $prod) {
    //some code...
    $product = Mage::getModel('catalog/product')
                     ->setStoreId(Mage::app()->getStore()->getId())
                     ->load($prod);
    $cart->addProduct($product->getId(), $qty) // here how i get the $qty of each product, if i put it manually it works, 2 for exemple, it add 2 for all products

}

【问题讨论】:

  • 如果你想连接ids和qtys,那么对于每个id都有一个对应的qty(或者相反,它没有问题),您应该创建一个关联数组,其中$productId 的值作为键,qty 的值作为值,所以你会得到类似:[106 => 4, 107 => 3, ...]。然后,您可以访问这两个值,id 作为键,qty 作为 foreach() 中的值。
  • 好主意,如何将两者关联起来? array_merge ?如果你能回答这个问题就好了
  • 你要找的函数是array_combine()

标签: php zend-framework zend-form


【解决方案1】:
array_combine($productIds,$productQtys)

结果:

array(
       [1639] => 6
       [1640] => 4
       [1641] => 3
       [1646] => 2
)

//Thanks to @Tobias F

【讨论】:

  • 这会给你你正在寻找的结果:)
【解决方案2】:

如果你的键是对应的,那么你可以将你的 foreach 扩展到 key=>value 构造。然后就可以直接使用qty数组中的key了。没有测试它,但它是这样的:

foreach($productIds as $key => $prod) {

    $product = Mage::getModel('catalog/product')
                     ->setStoreId(Mage::app()->getStore()->getId())
                     ->load($prod);
    $cart->addProduct($product->getId(), $qty[$key]) 
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2023-03-15
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 2020-05-17
    相关资源
    最近更新 更多