Случайные товары в "новинках", "рекомендуемых", "хитах продаж" и "акциях"

Тема в разделе "OpenCart", создана пользователем KuEdA, 18 окт 2015.

  1. KuEdA

    KuEdA

    Регистрация:
    20 сен 2014
    Сообщения:
    194
    Симпатии:
    36
    Здравствуйте, на сайте http://stylishjewel.ru/ хотелось бы сделать вывод товаров случайным образом в модулях такие как : "Последние", "Акции", "Рекомендуемые", "Хиты продаж", допустим в админке задал лимит на 3 вывода, а самих товаров там 20-30, и что бы они случайным образом каждый раз менялись. В ветке:
    http://wmasteru.org/threads/Чередование-товаров-в-модуле-рекомендуемые.9571/
    нашел вот такой образец рандомного вывода:
    Код:
    $this->data['products'] = array();
    $products = explode(',', $this->config->get('featured_product'));
    
    if (empty($setting['limit'])) {
       $setting['limit'] = 5;
    }
    
    $random_products = array();
    $product_keys = array_rand($products,$setting['limit']);
    foreach ($product_keys as $product_key) {
       $random_products[$product_key] = $products[$product_key];
    }
    
    $products = $random_products;
    Но что-то не могу с ним разобраться. "Последние", "Акции", "Рекомендуемые", "Хиты продаж" выводятся у меня через вкладки товаров 4в1. Когда я вставляю этот код для рекомендуемых в catalog/controller/module/product_tab.php
    Код:
    <?php
    class ControllerModuleProductTab extends Controller {
      
        protected function index($setting) {
    
            if(!isset($this->request->get['route']) || $this->request->get['route'] != 'product/product'){
            $this->document->addScript('catalog/view/javascript/jquery/tabs.js');
            }
    
            static $module = 0;
    
            $this->language->load('module/product_tab');
          
              $this->data['heading_title'] = $this->language->get('heading_title');
    
              $this->data['tab_latest'] = $this->language->get('tab_latest');
              $this->data['tab_featured'] = $this->language->get('tab_featured');
              $this->data['tab_bestseller'] = $this->language->get('tab_bestseller');
              $this->data['tab_special'] = $this->language->get('tab_special');
    
          
            $this->data['button_cart'] = $this->language->get('button_cart');
                  
            $this->load->model('catalog/product');
          
            // bestseller
              
                $bestseller_products = $this->model_catalog_product->getBestSellerProducts(25);
                $bestsellers = array();
              
                foreach ($bestseller_products as $bestseller_product) {
                    $bestsellers[] = $bestseller_product['product_id'];
                }
              
                // featured
    
                $products_featured = explode(',', $this->config->get('featured_product'));
    
                // labels config
    
                $config_labels = $this->config->get('intelligent_product_labels_module');
                if ( empty($config_labels) ) { $config_labels = array(); }
    
                // current class name
    
                $current_layout = get_class($this);
          
            $this->load->model('tool/image');
    
            //Latest Products
          
            $this->data['latest_products'] = array();
          
            $latest_results = $this->model_catalog_product->getLatestProducts($setting['limit']);
    
    
            foreach ($latest_results as $result) {
                if ($result['image']) {
    $results_img = $this->model_catalog_product->getProductImages($result['product_id']);
                    $dop_img = array();
                    foreach ($results_img as $result_img) {
                    if ($result_img['image']) {
                    $image_dop = $this->model_tool_image->resize($result_img['image'], $this->config->get('config_image_product_width'), $this->config->get('config_image_product_height'));
                    } else {
                    $image_dop = false;
                    }
                     $dop_img[] = $image_dop;
                    }
                    $image = $this->model_tool_image->resize($result['image'], $setting['image_width'], $setting['image_height']);
                } else {
                    $image = $this->model_tool_image->resize('no_image.jpg', $setting['image_width'], $setting['image_height']);
                }
                          
                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $price = false;
                }
                      
                if ((float)$result['special']) {
                    $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $special = false;
                }
              
                if ($this->config->get('config_review_status')) {
                    $rating = $result['rating'];
                } else {
                    $rating = false;
                }
              
                $mylabels = new Label($this->registry);
    
                $mylabels->labels = $config_labels;
                $mylabels->product_info = stripos($current_layout,'ControllerModuleFeatured') !== false ||
                                          stripos($current_layout,'ControllerModuleFakelatest') !== false ||
                                          stripos($current_layout,'ControllerModuleFakemostviewed') !== false ||
                                          stripos($current_layout,'ControllerModuleFakebestseller')!== false ||
                                          stripos($current_layout,'ControllerModuleBookoftheweek')!== false ||
                                          stripos($current_layout,'ControllerModuledealoftheday')!== false ||
                                          stripos($current_layout,'ControllerModulePreorders')!== false ? $product_info : $result;
                $mylabels->current_layout = $current_layout;
                $mylabels->current_layout_position = $setting['position'];
                $mylabels->products_featured = $products_featured;
                $mylabels->bestsellers = $bestsellers;
                $labels = $mylabels->RenderLabels();          
                $this->data['latest_products'][] = array(
                                    'labels' => $labels,
                    'product_id' => $result['product_id'],
                                    'dop_img' => $dop_img,
                    'thumb'        => $image,
                    'name'         => $result['name'],
                    'price'        => $price,
                    'special'      => $special,
                    'saving'     => ((float)$result['price'] ? round((($result['price'] - $result['special'])/$result['price'])*100, 0) : 0),
                    'rating'     => $rating,
                    'reviews'    => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
                    'href'         => $this->url->link('product/product', 'product_id=' . $result['product_id']),
                );
            }
    
            //Specials product
    
            $this->data['special_products'] = array();
    
                $special_data = array(
                'sort'  => 'pd.name',
                'order' => 'ASC',
                'start' => 0,
                'limit' => $setting['limit']
            );
    
    
          
            $special_results = $this->model_catalog_product->getProductSpecials($special_data);
    
            foreach ($special_results as $result) {
                if ($result['image']) {
    $results_img = $this->model_catalog_product->getProductImages($result['product_id']);
                    $dop_img = array();
                    foreach ($results_img as $result_img) {
                    if ($result_img['image']) {
                    $image_dop = $this->model_tool_image->resize($result_img['image'], $this->config->get('config_image_product_width'), $this->config->get('config_image_product_height'));
                    } else {
                    $image_dop = false;
                    }
                     $dop_img[] = $image_dop;
                    }
                    $image = $this->model_tool_image->resize($result['image'], $setting['image_width'], $setting['image_height']);
                } else {
                    $image = $this->model_tool_image->resize('no_image.jpg', $setting['image_width'], $setting['image_height']);
                }
                          
                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $price = false;
                }
                      
                if ((float)$result['special']) {
                    $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $special = false;
                }
              
                if ($this->config->get('config_review_status')) {
                    $rating = $result['rating'];
                } else {
                    $rating = false;
                }
              
                $mylabels = new Label($this->registry);
    
                $mylabels->labels = $config_labels;
                $mylabels->product_info = stripos($current_layout,'ControllerModuleFeatured') !== false ||
                                          stripos($current_layout,'ControllerModuleFakelatest') !== false ||
                                          stripos($current_layout,'ControllerModuleFakemostviewed') !== false ||
                                          stripos($current_layout,'ControllerModuleFakebestseller')!== false ||
                                          stripos($current_layout,'ControllerModuleBookoftheweek')!== false ||
                                          stripos($current_layout,'ControllerModuledealoftheday')!== false ||
                                          stripos($current_layout,'ControllerModulePreorders')!== false ? $product_info : $result;
                $mylabels->current_layout = $current_layout;
                $mylabels->current_layout_position = $setting['position'];
                $mylabels->products_featured = $products_featured;
                $mylabels->bestsellers = $bestsellers;
                $labels = $mylabels->RenderLabels();
              
                $this->data['special_products'][] = array(
                          'labels' => $labels,
                    'product_id' => $result['product_id'],
                    'dop_img' => $dop_img,
                    'thumb'        => $image,
                    'name'         => $result['name'],
                    'price'        => $price,
                    'special'      => $special,
                    'saving'     => ((float)$result['price'] ? round((($result['price'] - $result['special'])/$result['price'])*100, 0) : 0),
                    'rating'     => $rating,
                    'reviews'    => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
                    'href'         => $this->url->link('product/product', 'product_id=' . $result['product_id']),
                );
            }
    
            //BestSeller
            $this->data['bestseller_products'] = array();
    
            $bestseller_results = $this->model_catalog_product->getBestSellerProducts($setting['limit']);
          
            foreach ($bestseller_results as $result) {
                if ($result['image']) {
    $results_img = $this->model_catalog_product->getProductImages($result['product_id']);
                    $dop_img = array();
                    foreach ($results_img as $result_img) {
                    if ($result_img['image']) {
                    $image_dop = $this->model_tool_image->resize($result_img['image'], $this->config->get('config_image_product_width'), $this->config->get('config_image_product_height'));
                    } else {
                    $image_dop = false;
                    }
                     $dop_img[] = $image_dop;
                    }
                    $image = $this->model_tool_image->resize($result['image'], $setting['image_width'], $setting['image_height']);
                } else {
                    $image = $this->model_tool_image->resize('no_image.jpg', $setting['image_width'], $setting['image_height']);
                }
              
                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $price = false;
                }
                      
                if ((float)$result['special']) {
                    $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $special = false;
                }  
              
                if ($this->config->get('config_review_status')) {
                    $rating = $result['rating'];
                } else {
                    $rating = false;
                }
              
                $mylabels = new Label($this->registry);
    
                $mylabels->labels = $config_labels;
                $mylabels->product_info = stripos($current_layout,'ControllerModuleFeatured') !== false ||
                                          stripos($current_layout,'ControllerModuleFakelatest') !== false ||
                                          stripos($current_layout,'ControllerModuleFakemostviewed') !== false ||
                                          stripos($current_layout,'ControllerModuleFakebestseller')!== false ||
                                          stripos($current_layout,'ControllerModuleBookoftheweek')!== false ||
                                          stripos($current_layout,'ControllerModuledealoftheday')!== false ||
                                          stripos($current_layout,'ControllerModulePreorders')!== false ? $product_info : $result;
                $mylabels->current_layout = $current_layout;
                $mylabels->current_layout_position = $setting['position'];
                $mylabels->products_featured = $products_featured;
                $mylabels->bestsellers = $bestsellers;
                $labels = $mylabels->RenderLabels();
                              
                $this->data['bestseller_products'][] = array(
                        'labels' => $labels,
                    'product_id' => $result['product_id'],
                    'dop_img' => $dop_img,
                    'thumb'        => $image,
                    'name'         => $result['name'],
                    'price'        => $price,
                    'special'      => $special,
                    'saving'     => ((float)$result['price'] ? round((($result['price'] - $result['special'])/$result['price'])*100, 0) : 0),
                    'rating'     => $rating,
                    'reviews'    => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
                    'href'         => $this->url->link('product/product', 'product_id=' . $result['product_id']),
                );
            }
    
    
            //Featured
    
                    $this->data['featured_products'] = array();
    
            $products = explode(',', $this->config->get('featured_product'));      
    
            if (empty($setting['limit'])) {
                $setting['limit'] = 5;
            }
          
            $products = array_slice($products, 0, (int)$setting['limit']);
          
            foreach ($products as $product_id) {
                $product_info = $this->model_catalog_product->getProduct($product_id);
              
                if ($product_info) {
    $results_img = $this->model_catalog_product->getProductImages($product_info['product_id']);
                    $dop_img = array();
                    foreach ($results_img as $result_img) {
                    if ($result_img['image']) {
                    $image_dop = $this->model_tool_image->resize($result_img['image'], $setting['image_width'], $setting['image_height']);
                    } else {
                    $image_dop = false;
                    }
                     $dop_img[] = $image_dop;
                    }
                    if ($product_info['image']) {
                        $image = $this->model_tool_image->resize($product_info['image'], $setting['image_width'], $setting['image_height']);
                    } else {
                        $image = $this->model_tool_image->resize('no_image.jpg', $setting['image_width'], $setting['image_height']);
                    }
    
                    if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                        $price = $this->currency->format($this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                    } else {
                        $price = false;
                    }
                          
                    if ((float)$product_info['special']) {
                        $special = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                    } else {
                        $special = false;
                    }
                  
                    if ($this->config->get('config_review_status')) {
                        $rating = $product_info['rating'];
                    } else {
                        $rating = false;
                    }
                  
                    $mylabels = new Label($this->registry);
    
                $mylabels->labels = $config_labels;
                $mylabels->product_info = stripos($current_layout,'ControllerModuleFeatured') !== false ||
                                          stripos($current_layout,'ControllerModuleFakelatest') !== false ||
                                          stripos($current_layout,'ControllerModuleFakemostviewed') !== false ||
                                          stripos($current_layout,'ControllerModuleFakebestseller')!== false ||
                                          stripos($current_layout,'ControllerModuleBookoftheweek')!== false ||
                                          stripos($current_layout,'ControllerModuledealoftheday')!== false ||
                                          stripos($current_layout,'ControllerModulePreorders')!== false ? $product_info : $result;
                $mylabels->current_layout = $current_layout;
                $mylabels->current_layout_position = $setting['position'];
                $mylabels->products_featured = $products_featured;
                $mylabels->bestsellers = $bestsellers;
                $labels = $mylabels->RenderLabels();
                      
                    $this->data['featured_products'][] = array(
                                            'labels' => $labels,
                        'product_id' => $product_info['product_id'],
                        'dop_img' => $dop_img,
                        'thumb'        => $image,
                        'name'         => $product_info['name'],
                        'price'        => $price,
                        'special'      => $special,
                                            'saving'     => ((float)$product_info['price'] ? round((($product_info['price'] - $product_info['special'])/$product_info['price'])*100, 0) : 0),
                        'rating'     => $rating,
                        'reviews'    => sprintf($this->language->get('text_reviews'), (int)$product_info['reviews']),
                        'href'         => $this->url->link('product/product', 'product_id=' . $product_info['product_id']),
                    );
                }
            }
    
            $this->data['module'] = $module++;
    
            if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/product_tab.tpl')) {
                $this->template = $this->config->get('config_template') . '/template/module/product_tab.tpl';
            } else {
                $this->template = 'ava/template/module/product_tab.tpl';
            }
    
            $this->render();
        }
    }
    ?>
    таким образом
    Код:
                    $this->data['featured_products'] = array();
    
            $products = explode(',', $this->config->get('featured_product'));      
    
            if (empty($setting['limit'])) {
                $setting['limit'] = 5;
            }
          
            $random_products = array();
    $product_keys = array_rand($products,$setting['limit']);
    foreach ($product_keys as $product_key) {
       $random_products[$product_key] = $products[$product_key];
    }
    
    $products = $random_products;
            
    То появляется ошибка
    Код:
    Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /var/www/c381952/public_html/stylishjewel.ru/catalog/controller/module/product_tab.php on line 286Warning: Invalid argument supplied for foreach() in /var/www/c381952/public_html/stylishjewel.ru/catalog/controller/module/product_tab.php on line 287
    И вкладка "Рекомендуемые" не появляется. Помогите, пожалуйста, доработать код до нужного функционала. Заранее огромное спасибо.
     
  2. KuEdA

    KuEdA

    Регистрация:
    20 сен 2014
    Сообщения:
    194
    Симпатии:
    36
    Нашел сейчас вот такой вариант: https://opencartforum.com/topic/18785-rekomenduemye-randomno/page-2. Пишут, что полностью рабочий. Но у меня почему-то он опять не работает, когда прописываю этот код:
    Код:
    $this->data['latest_products'] = array();
        
            $latest_results = $this->model_catalog_product->getLatestProducts($setting['limit']);
    //ADD
    srand((float)microtime() * 1000000);
    shuffle($results);
    $results = array_slice($results, 0, $setting['limit']);
    //END
    
    то выдает вот такую ошибку:
    Код:
    Warning: shuffle() expects parameter 1 to be array, null given in /var/www/c381952/public_html/stylishjewel.ru/catalog/controller/module/product_tab.php on line 57Warning: array_slice() expects parameter 1 to be array, null given in /var/www/c381952/public_html/stylishjewel.ru/catalog/controller/module/product_tab.php on line 58
     
  3. Dotrox

    Dotrox Команда форума

    Регистрация:
    27 ноя 2012
    Сообщения:
    3.198
    Симпатии:
    1.306
    KuEdA, мозги включите и посмотрите на тексты ошибок.
    PHP:
    shuffle($results);
    Где у вас объявлена перемеренная $results? Правильно - нигде, ибо у вас $latest_results.

    И здесь та же история:
    PHP:
    array_slice($results0$setting['limit']);
    А по ошибке в первом посте: у вас в $setting['limit'] число больше, чем товаров для вывода.
     
    KuEdA нравится это.
  4. KuEdA

    KuEdA

    Регистрация:
    20 сен 2014
    Сообщения:
    194
    Симпатии:
    36
    Спасибо за ответ. Протупил я конечно. Поправил и все заработало:
    Код:
    $this->data['latest_products'] = array();
       
            $latest_results = $this->model_catalog_product->getLatestProducts($setting['limit']);
    //ADD
    srand((float)microtime() * 1000000);
    shuffle($latest_results);
    $latest_results = array_slice($latest_results, 0, $setting['limit']);
    //END