6cnitymi Posted October 30, 2021 Report Share Posted October 30, 2021 Приветствую, друзья! На форуме уже присутствует старая тема "Объединение товаров в варианты": На днях столкнулся с аналогичной проблемой, в связи с чем и отправился на поиски решения, найдя эту тему. В моём случае, решение оказалось муторным и не совсем удобным, т.к. каждое объединение необходимо вручную исправлять, потому решил его немного расширить, может кому-то тоже понадобится. Собственно, к сути - при выборе нескольких товаров, с одним, по сути, названием (например, "Термос Супер (Black)", "Термос Супер (White)", "Термос Супер (Yellow)"), при объединении, мы получим товар "Термос Супер" и три варианта - Black, White и Yellow. Понимаю, что формат выгрузки прайсов у кого-то может быть специфическим, но по моему опыту, чаще всего это именно вид "Категория Производитель Модель (Модификация)". Само решение: 1. В ProductsAdmin добавляем новую функцию (перед последней закрывающей фигурной скобкой): function longest_common_substring($words) { $words = array_map('strtolower', array_map('trim', $words)); $sort_by_strlen = create_function('$a, $b', 'if (strlen($a) == strlen($b)) { return strcmp($a, $b); } return (strlen($a) < strlen($b)) ? -1 : 1;'); usort($words, $sort_by_strlen); $longest_common_substring = array(); $shortest_string = str_split(array_shift($words)); while (sizeof($shortest_string)) { array_unshift($longest_common_substring, ''); foreach ($shortest_string as $ci => $char) { foreach ($words as $wi => $word) { if (!strstr($word, $longest_common_substring[0] . $char)) { break 2; } } $longest_common_substring[0].= $char; } array_shift($shortest_string); } usort($longest_common_substring, $sort_by_strlen); return array_pop($longest_common_substring); } 2. Немного меняем механику в блоке "combine": case 'combine': { $combine_id = $ids[0]; $parent_name = array(); $sub_variants = $this->variants->get_variants(array('product_id'=>$ids)); foreach ($sub_variants as $variant) { $native_product = $this->products->get_product((int)$variant->product_id); array_push($parent_name, $native_product->name); } $honor_name = $this->longest_common_substring($parent_name); foreach ($sub_variants as $variant) { $native_product = $this->products->get_product((int)$variant->product_id); $variant->product_id = $combine_id; $n = $native_product->name; $n = str_ireplace($honor_name, '', $n); $n = str_ireplace(')', '', $n); if (empty($variant->name)) $variant->name = $n; unset($variant->infinity); $this->variants->update_variant($variant->id, $variant); if (is_object($native_product) && ($native_product->id != $combine_id)) { $products_to_delete[] = $native_product; } } foreach ($products_to_delete as $p) { $this->products->delete_product((int)$p->id);} $this->products->update_product($combine_id, array('name'=>rtrim($honor_name," ("))); break; } Собственно, на этом все изменения. Код можно оптимизировать, например, убрав два цикла перебора вариантов в один, и тд Из явных минусов только один - родительский товар теряет регистр, вместо "Термос Супер Пупер М-1 (Black)" мы получаем "Термос супер пупер м-1", но это мелочи, не влияющие на работу. Надеюсь, решение кому-нибудь окажется полезным. Quote Link to post Share on other sites
sergeevizh Posted October 31, 2021 Report Share Posted October 31, 2021 12 часов назад, 6cnitymi сказал: $words = array_map('strtolower', array_map('trim', $words)); strtolower - преобразует все символы в нижний регистр Quote Link to post Share on other sites
6cnitymi Posted October 31, 2021 Author Report Share Posted October 31, 2021 1 час назад, alexivchenko сказал: strtolower - преобразует все символы в нижний регистр Да, благодарю! Функция взята с просторов гитхаба, потому не особо всматривался в неё Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.