[СДЕЛАЙ САМ] Фильтрация по множественным значениям.

Приветствую!
Задача: сделать фильтр по регионам в которых доступен продукт, при условии, что один продукт может быть доступен в нескольких регионах сразу.
В решении использовались раздел из документации и статья @Илья Уткин

<?php

class CustomFilter extends mse2FiltersHandler
{

    public function getPolyFieldValues(array $keys, array $ids)
    {
        $filters = array();

        $q = $this->modx->newQuery('msProductData');
        $q->where(array('id:IN' => $ids));
        $q->select('id,' . implode(',', $keys));
        $tstart = microtime(true);
        if ($q->prepare() && $q->stmt->execute()) {
            $this->modx->queryTime += microtime(true) - $tstart;
            $this->modx->executedQueries++;
            while ($row = $q->stmt->fetch(PDO::FETCH_ASSOC)) {
                foreach ($row as $k => $v) {
                    $values = json_decode($v, 1);
                    if ($k == 'id') {
                        continue;
                    } elseif(is_array($values)){
                        foreach ($values as $val) {
                            $filters[$k][$val][] = $row['id'];
                        }
                    }
                }
            }
        } else {
            $this->modx->log(modX::LOG_LEVEL_ERROR, "[mSearch2] Error on get filter params.\nQuery: " . $q->toSql() . "\nResponse: " . print_r($q->stmt->errorInfo(), 1));
        }

        return $filters;
    }

    public function buildPolyFieldFilter(array $values, $name = '')
    {
        if (count($values) < 2 && empty($this->config['showEmptyFilters'])) {
            return array();
        }
        $results = array();
        foreach ($values as $value => $ids) {
            $results[$value] = array(
                'title' => $value
            , 'value' => $value
            , 'type' => 'default'
            , 'resources' => $ids
            );
        }

        ksort($results);
        return $results;
    }


    public function filterPolyField(array $requested, array $values, array $ids)
    {

        $matched = array();
        $tmp = array_flip($ids);
        foreach ($requested as $value) {
            if (isset($values[$value])) {
                $resources = $values[$value];
                foreach ($resources as $id) {
                    if (isset($tmp[$id])) {
                        $matched[] = $id;
                    }
                }
            }
        }

        $match = $matched;
        $matched = array();
        $count = count($requested);
        $count_values = array_count_values($match);

        foreach ($count_values as $id => $value) {
            if ($value >= $count) {
                $matched[] = $id;
            } else {
                $matched[] = 0;
            }
        }
        //$this->modx->log(1, print_r($matched,1));
        return $matched;
    }

    public function getSuggestions($ids, array $request, array $current = array()) {}

}


Сам фильтр это select с одиночным выбором.
Артур Шевченко
29 апреля 2021, 16:05
modx.pro
1
1 452
+5
Поблагодарить автора Отправить деньги

Комментарии: 2

Павел Гвоздь
02 мая 2021, 08:20
0
Артур, я минуснул пост за простыню кода на главной. Прошу спрятать её под кат.
Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
2