Таблица сравнения для товаров подкатегории

Тема в разделе "Общие вопросы", создана пользователем max_1985, 23 дек 2020.

  1. max_1985

    max_1985 Новичок

    Сообщения:
    18
    Симпатии:
    2
    Здравствуйте!
    Помогите пожалуйста с кодом!
    В главной категории, подкатегории выводятся таким образом https://prnt.sc/w3cof3 , вместе с ссылками на товары.... Под картинками, есть кнопка сравнения, которая должна выводить таблицу сравнения товаров подкатегории по атрибутам (https://prnt.sc/w3s890)... Не получается вывести эти атрибуты, не пойму что упустил.

    Приведу код

    Контроллер
    PHP:
    $data['products_all'] = array();

    for( 
    $x 0$x count$data['categories'] ); $x++ ) {

        
    $cat $data['categories'][ $x ][ 'category_id' ];
        
    $data['products_all'][ $cat ] = array();


        
    $filter_data = array(
            
    'filter_category_id' => $cat,
            
    'sort'               => $sort,
            
    'order'              => $order,
            
    'start'              => ($page 1) * $limit,
            
    'limit'              => $limit
        
    );

        
    $product_total $this->model_catalog_product->getTotalProducts($filter_data);
        
    $results1 $this->model_catalog_product->getProducts($filter_data);
        
        
    $data['attribute_groups1'] = array();
      
       foreach (
    $results1 as $result) {
            
            if (
    $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')), $this->session->data['currency']);
                    } 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')), $this->session->data['currency']);
                    } else {
                        
    $special false;
            }

            if (
    $this->config->get('config_tax')) {
                        
    $tax $this->currency->format((float)$result['special'] ? $result['special'] : $result['price'], $this->session->data['currency']);
                    } else {
                        
    $tax false;
            }
            
            
    $attribute_data1 = array();
            

                    
    $attribute_groups1 $this->model_catalog_product->getProductAttributes($result['product_id']);

                    foreach (
    $attribute_groups1 as $attribute_group1) {
                        foreach (
    $attribute_group1['attribute'] as $attribute) {
                            
    $attribute_data1[$attribute['attribute_id']] = $attribute['text'];
                        }
                    }

            
    $data['products_all'][ $cat ][] = array(
                
    'product_id'  => $result['product_id'],
                
    'name'        => $result['name'],
                
    'price'       => $price,
                
    'special'     => $special,
                
    'tax'         => $tax,
                
    'minimum'     => $result['minimum'] > $result['minimum'] : 1,
                
    'model'       => $result['model'],
                
    'attribute'   => $attribute_data1,
                
    'href'        => $this->url->link('product/product''path=' $this->request->get['path'] . '&product_id=' $result['product_id'] . $url)

            );
            
            foreach (
    $attribute_groups1 as $attribute_group1) {
                        
    $data['attribute_groups1'][$attribute_group1['attribute_group_id']]['name'] = $attribute_group1['name'];

                        foreach (
    $attribute_group1['attribute'] as $attribute) {
                            
    $data['attribute_groups1'][$attribute_group1['attribute_group_id']]['attribute'][$attribute['attribute_id']]['name'] = $attribute['name'];
                        }
            }
            
        }
        
    }
    Шаблон
    PHP:
    <?php if ($categories) { ?>
          <div class="row category">
            <div class="subcats">
              <div>
    <?php foreach ($categories as $category) { ?>
    <div class="col-lg-4 col-md-6 col-sm-6 col-xs-12 bl-sk">   
                <div class="col-md-12 col-sm-12 col-xs-12">
                <h3 class="category-item-name"><a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a></h3>
                <hr class="category-item-line">
                <span class="h2m"><?php echo $category['meta_h1']; ?></span>
                </div>
    <div class="row">           
    <div class="col-lg-6 col-md-6 col-sm-6 hidden-xs">
    <a href="<?php echo $category['href']; ?>"><img class="img-sk" src="<?php echo $category['image']; ?>" alt="<?php echo $category['name']; ?>" /></a><br />
    <a class="sr" type="button" data-toggle="modal" data-target="#myModal-<?php echo $category['category_id']; ?>">Сравнить</a>


    <div id="myModal-<?php echo $category['category_id']; ?>" class="modal fade">
    <div class="modal-dialog">
    <div class="modal-content">
    <div class="modal-header"><button class="close" type="button" data-dismiss="modal">×</button>
    <h4 class="modal-title">Сравнение <?php echo $category['name']; ?></h4>
    </div>
    <div class="modal-body">

    <table class="table table-bordered">
    <thead>
    <tr>
    <th>Название</th>
    <?php foreach ($attribute_groups1 as $attribute_group1) { ?>
    <?php $i 
    0?>
    <?php 
    foreach ($attribute_group1['attribute'] as $attribute) { ?>
    <?php 
    if ($i 5) { ?>
    <th><?php echo $attribute['name']; ?></th>
    <?php $i++; ?>
    <?php 
    ?>
    <?php 
    ?>
    <th>Цена</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($products_all[$category['category_id']] as $product ) { ?>
    <tr>
    <td><a href="<?php echo $product['href']; ?>"><?php echo $product['name']; ?></a></td>
    <?php foreach ($attribute_groups1 as $attribute_group1) { ?>
    <?php $i 
    0?>
            <?php foreach ($attribute_group1['attribute'] as $key => $attribute) { ?>
    <?php 
    if ($i 5) { ?>
                <?php if (isset($product['attribute'][$key])) { ?>
                <td><?php echo $product['attribute'][$key]; ?></td>
                <?php } else { ?>
                <td></td>
                <?php ?>
    <?php 
    $i++; ?>
    <?php 
    ?>
    <?php 
    ?>
    <td><a type="button" class="btn btn-primary btn-block" onclick="cart.add('<?php echo $product['product_id']; ?>', '<?php echo $product['minimum']; ?>');"><?php echo $product['price']; ?></a></td>
    </tr>
    <?php ?>
    </tbody>
    </table>


    </div>
    <div class="modal-footer"><button class="btn btn-default" type="button" data-dismiss="modal">Закрыть</button></div>
    </div>
    </div>
    </div>

    </div>
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12 mp0">
    <ul class="tov-cat">
    <?php foreach ( $products_all$category['category_id'] ] as $product ) { ?>
    <li class="poster">
    <a href="<?php echo $product['href']; ?>"><?php echo $product['name']; ?></a>
    </li>
    <?php ?>
    </ul>
    </div>
    </div>
    </div>
    <?php ?>

              </div>
            </div>
          </div>
    <?php ?>
    За помощь, готов отблагодарить!
     
  2. max_1985

    max_1985 Новичок

    Сообщения:
    18
    Симпатии:
    2
    Попробовал вывести такую таблицу на странице подкатегории, вывелась нормально https://prnt.sc/w8if23, а вот тут https://prnt.sc/w3cof3 не хочет... Не пойму в чем разница.
    Контроллер
    PHP:
    $data['products_t'] = array();

    $filter_data_t = array(
                    
    'filter_category_id' => $category_id
                    
    //'filter_sub_category' => true,
                    //'filter_filter'      => $filter,
                    //'sort'               => $sort,
                    //'order'              => $order,
                    //'start'              => ($page - 1) * $limit,
                    //'limit'              => $limit
    );

    $product_total $this->model_catalog_product->getTotalProducts($filter_data_t);

    $products_t $this->model_catalog_product->getProducts($filter_data_t);

    $data['attribute_groups'] = array();

            foreach (
    $products_t as $product_info) {
                
    //$product_info = $this->model_catalog_product->getProduct($product_id);

                    
    if ($product_info['image']) {
                        
    $image $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_compare_width'), $this->config->get($this->config->get('config_theme') . '_image_compare_height'));
                    } else {
                        
    $image false;
                    }

                    if (
    $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')), $this->session->data['currency']);
                    } 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')), $this->session->data['currency']);
                    } else {
                        
    $special false;
                    }

                    
    $attribute_data = array();

                    
    $attribute_groups $this->model_catalog_product->getProductAttributes($product_info['product_id']);

                    foreach (
    $attribute_groups as $attribute_group) {
                        foreach (
    $attribute_group['attribute'] as $attribute) {
                            
    $attribute_data[$attribute['attribute_id']] = $attribute['text'];
                        }
                    }

                    
    $data['products_t'][] = array(
                        
    'product_id'   => $product_info['product_id'],
                        
    'name'         => $product_info['name'],
                        
    'thumb'        => $image,
                        
    'price'        => $price,
                        
    'special'      => $special,
                        
    'minimum'      => $product_info['minimum'] > $product_info['minimum'] : 1,
                        
    'rating'       => (int)$product_info['rating'],
                        
    'reviews'      => sprintf($this->language->get('text_reviews'), (int)$product_info['reviews']),
                        
    'attribute'    => $attribute_data,
                        
    'href'         => $this->url->link('product/product''product_id=' $product_info['product_id'])
                    );

                    foreach (
    $attribute_groups as $attribute_group) {
                        
    $data['attribute_groups'][$attribute_group['attribute_group_id']]['name'] = $attribute_group['name'];

                        foreach (
    $attribute_group['attribute'] as $attribute) {
                            
    $data['attribute_groups'][$attribute_group['attribute_group_id']]['attribute'][$attribute['attribute_id']]['name'] = $attribute['name'];
                        }
                    }
            }
    Шаблон
    HTML:
    <table class="table table-bordered">
    <tr>
    <th>Название</th>
    <?php foreach ($attribute_groups as $attribute_group) { ?>
    <?php $i = 0; ?>
    <?php foreach ($attribute_group['attribute'] as $attribute) { ?>
    <?php if ($i < 5) { ?>
    <th><?php echo $attribute['name']; ?></th>
    <?php } $i++; ?>
    <?php } ?>
    <?php } ?>
    <th>Цена</th>
    </tr>
    <?php foreach ($products_t as $product) { ?>
    <tr>
    <td><a href="<?php echo $product['href']; ?>"><?php echo $product['name']; ?></a></td>
    <?php foreach ($attribute_groups as $attribute_group) { ?>
    <?php $i = 0; ?>
    <?php foreach ($attribute_group['attribute'] as $key => $attribute) { ?>
    <?php if ($i < 5) { ?>
                <?php if (isset($product['attribute'][$key])) { ?>
                <td><?php echo $product['attribute'][$key]; ?></td>
                <?php } else { ?>
                <td></td>
                <?php } ?>   
    <?php } $i++; ?>
    <?php } ?>
    <?php } ?>
    <td><a type="button" class="btn btn-primary btn-block" onclick="cart.add('<?php echo $product['product_id']; ?>', '<?php echo $product['minimum']; ?>');"><?php echo $product['price']; ?></a></td>
    </tr>
    <?php } ?>
    </table>
     
  3. Ravilr

    Ravilr Специалист

    Сообщения:
    3.864
    Симпатии:
    1.059
    А вот тут это где? Лучше слова таблица сравнения не указывайте в задачи, так как происходит путаница со штатным функционалом сравнения товаров. У вас же по сути просто товары в виде прайса со всем атрибутами.
     
  4. max_1985

    max_1985 Новичок

    Сообщения:
    18
    Симпатии:
    2
    При нажатии на кнопку сравнить, должна появиться таблица, сейчас она без атрибутов https://prnt.sc/w8ylft
     
  5. Ravilr

    Ravilr Специалист

    Сообщения:
    3.864
    Симпатии:
    1.059
    Посмотрите в контроллере, в переменной $attribute_groups есть вообще данные?
    PHP:
    var_dump($attribute_groups);
    И далее по коду. Поймете на каком моменте потеряли массив.
     
  6. max_1985

    max_1985 Новичок

    Сообщения:
    18
    Симпатии:
    2
    Если делаю так, так то ничего не выводит... Или я может не так понял?
    PHP:
    <?php foreach ($attribute_groups1 as $attribute_group1) { ?>
    <?php var_dump
    ($attribute_groups1); ?>
    <?php $i 
    0?>
    <?php 
    foreach ($attribute_group1['attribute'] as $attribute) { ?>
    <?php 
    if ($i 5) { ?>
    <th><?php echo $attribute['name']; ?></th>
    <?php $i++; ?>
    <?php 
    ?>
    <?php 
    ?>
    Спасибо что отозвались!
     
  7. Ravilr

    Ravilr Специалист

    Сообщения:
    3.864
    Симпатии:
    1.059
    Можете конечно и от шаблона искать причину, но я же все таки говорил про контроллер.
    Вставьте дамп перед
    PHP:
    foreach ($attribute_groups as $attribute_group) {
    и посмотрите. Потом далее ниже..
     
  8. max_1985

    max_1985 Новичок

    Сообщения:
    18
    Симпатии:
    2
    Выдало на странице кучу такого
    Код:
    array(1) { [0]=> array(3) { ["attribute_group_id"]=> string(1) "7" ["name"]=> string(28) "Характеристики" ["attribute"]=> array(8) { [0]=> array(3) { ["attribute_id"]=> string(2) "13" ["name"]=> string(16) "Радиус, м" ["text"]=> string(3) "120" } [1]=> array(3) { ["attribute_id"]=> string(2) "35" ["name"]=> string(15) "Размеры " ["text"]=> string(68) "160 x 160 x 32.65 мм 315 г (300 г — без крепления)" } [2]=> array(3) { ["attribute_id"]=> string(2) "32" ["name"]=> string(24) "Стандарты Wi-Fi" ["text"]=> string(31) "802.11a/b/g/n/r/k/v/ac/ac-wave2" } [3]=> array(3) { ["attribute_id"]=> string(2) "34" ["name"]=> string(39) "Мощность передатчика" ["text"]=> string(9) "26 дБм" } [4]=> array(3) { ["attribute_id"]=> string(2) "12" ["name"]=> string(22) 
     
  9. max_1985

    max_1985 Новичок

    Сообщения:
    18
    Симпатии:
    2
    Когда делаю так
    PHP:
    foreach ($attribute_groups1 as $attribute_group1) {
                        
    $data['attribute_groups1'][$attribute_group1['attribute_group_id']]['name'] = $attribute_group1['name'];
    var_dump($attribute_group1);
                        foreach (
    $attribute_group1['attribute'] as $attribute) {
                            
    $data['attribute_groups1'][$attribute_group1['attribute_group_id']]['attribute'][$attribute['attribute_id']]['name'] = $attribute['name'];
                        }
            }
    Тоже выдает кучу всего
     
  10. Ravilr

    Ravilr Специалист

    Сообщения:
    3.864
    Симпатии:
    1.059
    Вы сами не запутались? То $attribute_group1[
    то без 1. Видимо вы просто как то прыгаете по коду, поэтому ничего не получается.

    Запомните одно, если перед рендерингом в переменной $data['хххх
    что то есть, то и в шаблоне должно это в переменной $xxxx появится.
    Другие случаи это или обнулили переменную ниже по коду или формируете данные ниже строки рендеринга...
    PHP:
    $this->response->setOutput($this->load->view('product/category'$data));
     
  11. max_1985

    max_1985 Новичок

    Сообщения:
    18
    Симпатии:
    2
    Это просто у меня один код для вывода таблицы в подкатегории под списком товаров $attribute_group, а другой для вывода всплывающем окне $attribute_group1.
     
  12. max_1985

    max_1985 Новичок

    Сообщения:
    18
    Симпатии:
    2
    Когда вывожу в шаблоне
    PHP:
    <?php var_dump($attribute_groups1);?>
    <?php 
    foreach ($attribute_groups1 as $attribute_group1) { ?>
    <?php $i 
    0?>
            <?php foreach ($attribute_group1['attribute'] as $key => $attribute) { ?>
    <?php 
    if ($i 5) { ?>
                <?php if (isset($product['attribute'][$key])) { ?>
                <td><?php echo $product['attribute'][$key]; ?></td>
                <?php } else { ?>
                <td></td>
                <?php ?>
    <?php 
    $i++; ?>
    <?php 
    ?>
    <?php 
    ?>
    то выдает такое https://prnt.sc/w92z97
     
  13. Ravilr

    Ravilr Специалист

    Сообщения:
    3.864
    Симпатии:
    1.059
    Выше я все описал, почему может не доходить до шаблона. Проверяйте.