提问者:小点点

如何避免在foreach循环创建的一行中重复字符串?


在尝试了一些没有成功的方法之后,我必须放弃,在这里问一下这个。

所以我有一个数组$PRODUCT_VAR_TPL_LIST=array(); 输出如下所示:

Shop1m  |  Pruduct 12  
Shop1m  |  Product 366 
Shop1m  |  Product 66 
Shop3a  |  Product 89 
Shop3a  |  Product 5   
Shop55  |  Product 6  

我想避免对第1列中的字符串进行都柏林化--输出必须如下所示:

Shop1m  |  Pruduct 12  
        |  Product 366
        |  Product 66  
Shop3a  |  Product 89 
        |  Product 5  
Shop55  |  Product 6  

PHP代码是:

                    $product_var_tpl_list = array();
                    foreach ($order->product_list as $product) {
                        $price = Product::getPriceStatic((int)$product['id_product'], false, ($product['id_product_attribute'] ? (int)$product['id_product_attribute'] : null), 6, null, false, true, $product['cart_quantity'], false, (int)$order->id_customer, (int)$order->id_cart, (int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                        $price_wt = Product::getPriceStatic((int)$product['id_product'], true, ($product['id_product_attribute'] ? (int)$product['id_product_attribute'] : null), 2, null, false, true, $product['cart_quantity'], false, (int)$order->id_customer, (int)$order->id_cart, (int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});

                        $product_price = Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt;

                        //here is data about the seller
                        $idProduct = (int)$product['id_product'];
                        $SellerInfoOverride = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'wk_mp_seller_product`  WHERE `id_ps_product` = '.(int) $idProduct);
                        foreach ($SellerInfoOverride as $key => $value) {
                            $sellerid = $value['id_seller'];
                            //$seller = $mpSeller->getSeller($value['id_seller'], $this->context->language->id);
                            $SellerInfoDetails = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'wk_mp_seller`  WHERE `id_seller` = '.(int) $sellerid);
                            foreach ($SellerInfoDetails as $key => $value) {
                                $seller_name = $value['shop_name_unique'];
                            }
                        }

                        $product_var_tpl = array(

                            'reference' => $seller_name,
                            'name' => $product['name'].(isset($product['attributes']) ? ' - '.$product['attributes'] : ''),
                            'unit_price' => Tools::displayPrice($product_price, $this->context->currency, false),
                            'price' => Tools::displayPrice($product_price * $product['quantity'], $this->context->currency, false),
                            'quantity' => $product['quantity'],
                            'customization' => array()

                        );


                        $customized_datas = Product::getAllCustomizedDatas((int)$order->id_cart);
                        if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
                            $product_var_tpl['customization'] = array();
                            foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) {
                                $customization_text = '';
                                if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
                                    foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
                                        $customization_text .= $text['name'].': '.$text['value'].'<br />';
                                    }
                                }

                                if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
                                    $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])).'<br />';
                                }

                                $customization_quantity = (int)$product['customization_quantity'];

                                $product_var_tpl['customization'][] = array(
                                    'customization_text' => $customization_text,
                                    'customization_quantity' => $customization_quantity,
                                    'quantity' => Tools::displayPrice($customization_quantity * $product_price, $this->context->currency, false)
                                );
                            }
                        }

                        $product_var_tpl_list[] = $product_var_tpl;
                        // Check if is not a virutal product for the displaying of shipping
                        if (!$product['is_virtual']) {
                            $virtual_product &= false;
                        }
                    } // end foreach ($products)

                    // this will sort the output by alphabetical order based on reference value
                    usort($product_var_tpl_list, function($a, $b) {  
                            return strcmp($a['reference'], $b['reference']);
                    });

共2个答案

匿名用户

正如上面的评论所指出的,您的问题中有几个部分有点模糊,主要是您的数组数据的结构。 正因为如此,我在下面的回答中做了一些假设。 注意,当它工作时,您可能需要稍微修改它以适应您的特定用例:

/*
 *  Original Data
 */
$data = [
    [ "key" => "Shop1m", "value" => "Product 12" ],    
    [ "key" => "Shop1m", "value" => "Product 366" ],
    [ "key" => "Shop1m", "value" => "Product 66" ],
    [ "key" => "Shop3a", "value" => "Product 89" ],
    [ "key" => "Shop3a", "value" => "Product 5" ],
    [ "key" => "Shop55", "value" => "Product 6" ]
];

/*
 *  Let's organize the data more like you'd like the output
 *  to be. We'll bring the initial keys to the forefront by
 *  creating a multi-dimensional array where all of the
 *  related products are grouped under their appropriate
 *  key header.
 */
$altered_data = [];

foreach($data as $entry) {
    if(!isset($altered_data[$entry["key"]])) {
        $altered_data[$entry["key"]] = [];
    }
    $altered_data[$entry["key"]][] = $entry["value"];
}

/*
 *  Now we'll output the data. This becomes trivial with a
 *  double "for" loop (i.e. "foreach" + "for" loops) without
 *  the need for keeping track of the previous header.
 */
echo "<table><tbody>";

foreach($altered_data as $key => $value) {
    for($a = 0, $len = count($value); $a < $len; $a++) {
      echo "<tr>";
      echo (0 === $a) ? "<td>" . $key . "</td>" : "<td></td>";
      echo "<td>" . $value[$a] . "</td>";
    }
}

echo "</tbody></table>";

匿名用户

我的回答是一般性的。

您有一个包含referencename列的数组,其中reference是shop。

将它们分组:

$productsGroupedByReference = [];
foreach($product_var_tpl AS $product) :
  if (!isset($productsGroupedByReference[$product['reference']])) {
    $productsGroupedByReference[$product['reference']] = [];
  }
  $productsGroupedByReference[$product['reference']][] = $product;
endforeach;

然后输出:

foreach($productsGroupedByReference AS $reference => $products) :
  print($reference.":\n");
  foreach($products AS $product) :
    print($product['name']."\n");
  endforeach;
  print("\n\n");
endforeach;