当前位置: 首页>>代码示例>>PHP>>正文


PHP Collator::compare方法代码示例

本文整理汇总了PHP中Collator::compare方法的典型用法代码示例。如果您正苦于以下问题:PHP Collator::compare方法的具体用法?PHP Collator::compare怎么用?PHP Collator::compare使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Collator的用法示例。


在下文中一共展示了Collator::compare方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: compare

 /**
  * Compare two strings.
  *
  * @param string $a
  * @param string $b
  *
  * @return int
  */
 public function compare($a, $b)
 {
     if (isset($this->collator)) {
         $a = (string) $a;
         $b = (string) $b;
         if ($this->caseSensitive) {
             $result = $this->collator->compare($a, $b);
         } else {
             $array = array($a, $b);
             if ($this->sort($array) === false) {
                 $result = false;
             } else {
                 $ia = array_search($a, $array);
                 if ($ia === 1) {
                     $result = 1;
                 } else {
                     $ib = array_search($b, $array);
                     if ($ib === 1) {
                         $result = -1;
                     } else {
                         $result = 0;
                     }
                 }
             }
         }
     } else {
         $a = $this->normalize($a);
         $b = $this->normalize($b);
         $result = $this->caseSensitive ? strnatcmp($a, $b) : strnatcasecmp($a, $b);
     }
     return $result;
 }
开发者ID:win10calendar,项目名称:3rdparty,代码行数:40,代码来源:Comparer.php

示例2: compare

 /**
  * @param string $a
  * @param string $b
  *
  * @return int
  */
 public function compare($a, $b)
 {
     if ($this->collator instanceof \Collator) {
         return $this->collator->compare($a, $b);
     } else {
         return $a == $b ? 0 : ($a > $b ? 1 : -1);
     }
 }
开发者ID:anime-db,项目名称:catalog-bundle,代码行数:14,代码来源:ViewSorter.php

示例3: getFinancialInstitutions

 public function getFinancialInstitutions()
 {
     /** @var Wirecard_CheckoutSeamless_Helper_Data $helper */
     $helper = Mage::helper('wirecard_checkoutseamless');
     $cl = new WirecardCEE_QMore_BackendClient($helper->getBackendConfigArray());
     $response = $cl->getFinancialInstitutions($this->getMethod()->getPaymentMethodType());
     if (!$response->hasFailed()) {
         $ret = $response->getFinancialInstitutions();
         $c = null;
         if (class_exists('Collator')) {
             $c = new Collator('root');
         }
         uasort($ret, function ($a, $b) use($c) {
             if ($c === null) {
                 return strcmp($a['id'], $b['id']);
             } else {
                 return $c->compare($a['name'], $b['name']);
             }
         });
         return $ret;
     } else {
         $helper->log(__METHOD__ . ':' . print_r($response->getErrors(), true), LOG_WARNING);
         return array();
     }
 }
开发者ID:wirecard,项目名称:magento-wcs,代码行数:25,代码来源:Abstract.php

示例4: generateFirstChars


//.........这里部分代码省略.........
         if (!isset($this->weights[$cp])) {
             // Non-printable, ignore
             continue;
         }
         foreach (StringUtils::explode('[', $allWeights) as $weightStr) {
             preg_match_all('/[*.]([0-9A-F]+)/', $weightStr, $m);
             if (!empty($m[1])) {
                 if ($m[1][0] !== '0000') {
                     $primary .= '.' . $m[1][0];
                 }
                 if ($m[1][2] !== '0000') {
                     $tertiary .= '.' . $m[1][2];
                 }
             }
         }
         $this->weights[$cp] = $primary;
         if ($tertiary === '.0008' || $tertiary === '.000E') {
             $goodTertiaryChars[$cp] = true;
         }
     }
     fclose($file);
     // Identify groups of characters with the same primary weight
     $this->groups = array();
     asort($this->weights, SORT_STRING);
     $prevWeight = reset($this->weights);
     $group = array();
     foreach ($this->weights as $cp => $weight) {
         if ($weight !== $prevWeight) {
             $this->groups[$prevWeight] = $group;
             $prevWeight = $weight;
             if (isset($this->groups[$weight])) {
                 $group = $this->groups[$weight];
             } else {
                 $group = array();
             }
         }
         $group[] = $cp;
     }
     if ($group) {
         $this->groups[$prevWeight] = $group;
     }
     // If one character has a given primary weight sequence, and a second
     // character has a longer primary weight sequence with an initial
     // portion equal to the first character, then remove the second
     // character. This avoids having characters like U+A732 (double A)
     // polluting the basic latin sort area.
     foreach ($this->groups as $weight => $group) {
         if (preg_match('/(\\.[0-9A-F]*)\\./', $weight, $m)) {
             if (isset($this->groups[$m[1]])) {
                 unset($this->groups[$weight]);
             }
         }
     }
     ksort($this->groups, SORT_STRING);
     // Identify the header character in each group
     $headerChars = array();
     $prevChar = "";
     $tertiaryCollator = new Collator('root');
     $primaryCollator = new Collator('root');
     $primaryCollator->setStrength(Collator::PRIMARY);
     $numOutOfOrder = 0;
     foreach ($this->groups as $weight => $group) {
         $uncomposedChars = array();
         $goodChars = array();
         foreach ($group as $cp) {
             if (isset($goodTertiaryChars[$cp])) {
                 $goodChars[] = $cp;
             }
             if (!isset($this->mappedChars[$cp])) {
                 $uncomposedChars[] = $cp;
             }
         }
         $x = array_intersect($goodChars, $uncomposedChars);
         if (!$x) {
             $x = $uncomposedChars;
             if (!$x) {
                 $x = $group;
             }
         }
         // Use ICU to pick the lowest sorting character in the selection
         $tertiaryCollator->sort($x);
         $cp = $x[0];
         $char = UtfNormal\Utils::codepointToUtf8($cp);
         $headerChars[] = $char;
         if ($primaryCollator->compare($char, $prevChar) <= 0) {
             $numOutOfOrder++;
             /*
             				printf( "Out of order: U+%05X > U+%05X\n",
             					utf8ToCodepoint( $prevChar ),
             					utf8ToCodepoint( $char ) );
             */
         }
         $prevChar = $char;
         if ($this->debugOutFile) {
             fwrite($this->debugOutFile, sprintf("%05X %s %s (%s)\n", $cp, $weight, $char, implode(' ', array_map('UtfNormal\\Utils::codepointToUtf8', $group))));
         }
     }
     print "Out of order: {$numOutOfOrder} / " . count($headerChars) . "\n";
     fwrite($outFile, serialize($headerChars));
 }
开发者ID:MediaWiki-stable,项目名称:1.26.1,代码行数:101,代码来源:generateCollationData.php

示例5: getFirstLetterData

 function getFirstLetterData()
 {
     if ($this->firstLetterData !== null) {
         return $this->firstLetterData;
     }
     $cache = wfGetCache(CACHE_ANYTHING);
     $cacheKey = wfMemcKey('first-letters', $this->locale, $this->digitTransformLanguage->getCode(), self::getICUVersion());
     $cacheEntry = $cache->get($cacheKey);
     if ($cacheEntry && isset($cacheEntry['version']) && $cacheEntry['version'] == self::FIRST_LETTER_VERSION) {
         $this->firstLetterData = $cacheEntry;
         return $this->firstLetterData;
     }
     // Generate data from serialized data file
     if (isset(self::$tailoringFirstLetters[$this->locale])) {
         $letters = wfGetPrecompiledData("first-letters-root.ser");
         // Append additional characters
         $letters = array_merge($letters, self::$tailoringFirstLetters[$this->locale]);
         // Remove unnecessary ones, if any
         if (isset(self::$tailoringFirstLetters['-' . $this->locale])) {
             $letters = array_diff($letters, self::$tailoringFirstLetters['-' . $this->locale]);
         }
         // Apply digit transforms
         $digits = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
         $letters = array_diff($letters, $digits);
         foreach ($digits as $digit) {
             $letters[] = $this->digitTransformLanguage->formatNum($digit, true);
         }
     } else {
         $letters = wfGetPrecompiledData("first-letters-{$this->locale}.ser");
         if ($letters === false) {
             throw new MWException("MediaWiki does not support ICU locale " . "\"{$this->locale}\"");
         }
     }
     /* Sort the letters.
      *
      * It's impossible to have the precompiled data file properly sorted,
      * because the sort order changes depending on ICU version. If the
      * array is not properly sorted, the binary search will return random
      * results.
      *
      * We also take this opportunity to remove primary collisions.
      */
     $letterMap = array();
     foreach ($letters as $letter) {
         $key = $this->getPrimarySortKey($letter);
         if (isset($letterMap[$key])) {
             // Primary collision
             // Keep whichever one sorts first in the main collator
             if ($this->mainCollator->compare($letter, $letterMap[$key]) < 0) {
                 $letterMap[$key] = $letter;
             }
         } else {
             $letterMap[$key] = $letter;
         }
     }
     ksort($letterMap, SORT_STRING);
     /* Remove duplicate prefixes. Basically if something has a sortkey
      * which is a prefix of some other sortkey, then it is an
      * expansion and probably should not be considered a section
      * header.
      *
      * For example 'þ' is sometimes sorted as if it is the letters
      * 'th'. Other times it is its own primary element. Another
      * example is '₨'. Sometimes its a currency symbol. Sometimes it
      * is an 'R' followed by an 's'.
      *
      * Additionally an expanded element should always sort directly
      * after its first element due to they way sortkeys work.
      *
      * UCA sortkey elements are of variable length but no collation
      * element should be a prefix of some other element, so I think
      * this is safe. See:
      * - https://ssl.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm
      * - http://site.icu-project.org/design/collation/uca-weight-allocation
      *
      * Additionally, there is something called primary compression to
      * worry about. Basically, if you have two primary elements that
      * are more than one byte and both start with the same byte then
      * the first byte is dropped on the second primary. Additionally
      * either \x03 or \xFF may be added to mean that the next primary
      * does not start with the first byte of the first primary.
      *
      * This shouldn't matter much, as the first primary is not
      * changed, and that is what we are comparing against.
      *
      * tl;dr: This makes some assumptions about how icu implements
      * collations. It seems incredibly unlikely these assumptions
      * will change, but nonetheless they are assumptions.
      */
     $prev = false;
     $duplicatePrefixes = array();
     foreach ($letterMap as $key => $value) {
         // Remove terminator byte. Otherwise the prefix
         // comparison will get hung up on that.
         $trimmedKey = rtrim($key, "");
         if ($prev === false || $prev === '') {
             $prev = $trimmedKey;
             // We don't yet have a collation element
             // to compare against, so continue.
             continue;
//.........这里部分代码省略.........
开发者ID:Acidburn0zzz,项目名称:mediawiki,代码行数:101,代码来源:Collation.php

示例6: renderPage

function renderPage()
{
    $LINKSDB = new LinkDB($GLOBALS['config']['DATASTORE'], isLoggedIn(), $GLOBALS['config']['HIDE_PUBLIC_LINKS'], $GLOBALS['redirector'], $GLOBALS['config']['REDIRECTOR_URLENCODE']);
    $updater = new Updater(read_updates_file($GLOBALS['config']['UPDATES_FILE']), $GLOBALS, $LINKSDB, isLoggedIn());
    try {
        $newUpdates = $updater->update();
        if (!empty($newUpdates)) {
            write_updates_file($GLOBALS['config']['UPDATES_FILE'], $updater->getDoneUpdates());
        }
    } catch (Exception $e) {
        die($e->getMessage());
    }
    $PAGE = new PageBuilder();
    $PAGE->assign('linkcount', count($LINKSDB));
    $PAGE->assign('privateLinkcount', count_private($LINKSDB));
    // Determine which page will be rendered.
    $query = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
    $targetPage = Router::findPage($query, $_GET, isLoggedIn());
    // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
    // Then assign generated data to RainTPL.
    $common_hooks = array('includes', 'header', 'footer');
    $pluginManager = PluginManager::getInstance();
    foreach ($common_hooks as $name) {
        $plugin_data = array();
        $pluginManager->executeHooks('render_' . $name, $plugin_data, array('target' => $targetPage, 'loggedin' => isLoggedIn()));
        $PAGE->assign('plugins_' . $name, $plugin_data);
    }
    // -------- Display login form.
    if ($targetPage == Router::$PAGE_LOGIN) {
        if ($GLOBALS['config']['OPEN_SHAARLI']) {
            header('Location: ?');
            exit;
        }
        // No need to login for open Shaarli
        $token = '';
        if (ban_canLogin()) {
            $token = getToken();
        }
        // Do not waste token generation if not useful.
        $PAGE->assign('token', $token);
        if (isset($_GET['username'])) {
            $PAGE->assign('username', escape($_GET['username']));
        }
        $PAGE->assign('returnurl', isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : '');
        $PAGE->renderPage('loginform');
        exit;
    }
    // -------- User wants to logout.
    if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) {
        invalidateCaches($GLOBALS['config']['PAGECACHE']);
        logout();
        header('Location: ?');
        exit;
    }
    // -------- Picture wall
    if ($targetPage == Router::$PAGE_PICWALL) {
        // Optionally filter the results:
        $links = $LINKSDB->filterSearch($_GET);
        $linksToDisplay = array();
        // Get only links which have a thumbnail.
        foreach ($links as $link) {
            $permalink = '?' . escape(smallhash($link['linkdate']));
            $thumb = lazyThumbnail($link['url'], $permalink);
            if ($thumb != '') {
                $link['thumbnail'] = $thumb;
                // Thumbnail HTML code.
                $linksToDisplay[] = $link;
                // Add to array.
            }
        }
        $data = array('linksToDisplay' => $linksToDisplay);
        $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => isLoggedIn()));
        foreach ($data as $key => $value) {
            $PAGE->assign($key, $value);
        }
        $PAGE->renderPage('picwall');
        exit;
    }
    // -------- Tag cloud
    if ($targetPage == Router::$PAGE_TAGCLOUD) {
        $tags = $LINKSDB->allTags();
        // We sort tags alphabetically, then choose a font size according to count.
        // First, find max value.
        $maxcount = 0;
        foreach ($tags as $value) {
            $maxcount = max($maxcount, $value);
        }
        // Sort tags alphabetically: case insensitive, support locale if avalaible.
        uksort($tags, function ($a, $b) {
            // Collator is part of PHP intl.
            if (class_exists('Collator')) {
                $c = new Collator(setlocale(LC_COLLATE, 0));
                if (!intl_is_failure(intl_get_error_code())) {
                    return $c->compare($a, $b);
                }
            }
            return strcasecmp($a, $b);
        });
        $tagList = array();
        foreach ($tags as $key => $value) {
//.........这里部分代码省略.........
开发者ID:toneiv,项目名称:Shaarli,代码行数:101,代码来源:index.php

示例7: compare

 /**
  * Locale aware comparison of two strings.
  *
  * Returns:
  *   1 if str1 is greater than str2
  *   0 if str1 is equal to str2
  *  -1 if str1 is less than str2
  *
  * @param string $str1 first string to compare
  * @param string $str2 second string to compare
  * @return int
  */
 public static function compare($str1, $str2) {
     if (self::ensure_collator_available()) {
         return self::$collator->compare($str1, $str2);
     }
     return strcmp($str1, $str2);
 }
开发者ID:,项目名称:,代码行数:18,代码来源:

示例8: finishView

 public function finishView(FormView $view, FormInterface $form, array $options)
 {
     if ($view->children['country']->vars['choice_translation_domain'] === false) {
         return;
     }
     $collator = new \Collator($this->translator->getLocale());
     $translator = $this->translator;
     $sortFunction = function ($a, $b) use($collator, $translator) {
         return $collator->compare($translator->trans($a->label), $translator->trans($b->label));
     };
     usort($view->children['country']->vars['choices'], $sortFunction);
     if (array_key_exists('state', $view->children) && $view->children['state']->vars['choice_translation_domain']) {
         usort($view->children['state']->vars['choices'], $sortFunction);
     }
     if (array_key_exists('city', $view->children) && $view->children['city']->vars['choice_translation_domain']) {
         usort($view->children['city']->vars['choices'], $sortFunction);
     }
 }
开发者ID:hackultura,项目名称:login-cidadao,代码行数:18,代码来源:CitySelectorComboType.php

示例9: strcmp

 /**
  * Сравнение строк
  *
  * @param   string|null    $s1
  * @param   string|null    $s2
  * @param   string         $locale   For example, 'en_CA', 'ru_RU'
  * @return  int|bool|null  Returns FALSE if error occurred
  *                         Returns < 0 if $s1 is less than $s2;
  *                                 > 0 if $s1 is greater than $s2;
  *                                 0 if they are equal.
  */
 public static function strcmp($s1, $s2, $locale = '')
 {
     if (!ReflectionTypeHint::isValid()) {
         return false;
     }
     if (is_null($s1) || is_null($s2)) {
         return null;
     }
     if (!function_exists('collator_create')) {
         return strcmp($s1, $s2);
     }
     # PHP 5 >= 5.3.0, PECL intl >= 1.0.0
     # If empty string ("") or "root" are passed, UCA rules will be used.
     $c = new Collator($locale);
     if (!$c) {
         # Returns an "empty" object on error. You can use intl_get_error_code() and/or intl_get_error_message() to know what happened.
         trigger_error(intl_get_error_message(), E_USER_WARNING);
         return false;
     }
     return $c->compare($s1, $s2);
 }
开发者ID:snidima,项目名称:rusp,代码行数:32,代码来源:UTF8.php

示例10: compareTo

 /**
  * @inheritdoc
  *
  * @param Group $other
  */
 public function compareTo($other)
 {
     $ref1 = strtoupper($this->getReference());
     $ref2 = strtoupper($other->getReference());
     $c = new \Collator('en');
     return $c->compare($ref1, $ref2);
 }
开发者ID:SURFnet,项目名称:grouphub,代码行数:12,代码来源:Group.php

示例11: sortByName

 /**
  * Sort result by name.
  * If \Collator exists (from ext/intl), the $locale argument will be used
  * for its constructor. Else, strcmp() will be used.
  * Example:
  *     $this->sortByName('fr_FR');
  *
  * @param   string  $locale   Locale.
  * @return  \Hoa\File\Finder
  */
 public function sortByName($locale = 'root')
 {
     if (true === class_exists('Collator', false)) {
         $collator = new \Collator($locale);
         $this->_sorts[] = function (\SplFileInfo $a, \SplFileInfo $b) use($collator) {
             return $collator->compare($a->getPathname(), $b->getPathname());
         };
     } else {
         $this->_sorts[] = function (\SplFileInfo $a, \SplFileInfo $b) {
             return strcmp($a->getPathname(), $b->getPathname());
         };
     }
     return $this;
 }
开发者ID:shulard,项目名称:File,代码行数:24,代码来源:Finder.php

示例12: compareTo

 /**
  * Compares this string against a given string lexicographically
  * @param static $obj
  * @return int -1, 0, or 1 depending on order
  * @throws \InvalidArgumentException if comparable type is incomparable
  */
 public function compareTo($obj)
 {
     if (!$obj instanceof static) {
         throw new \InvalidArgumentException('$obj is not a comparable instance');
     }
     $coll = new \Collator('');
     return $coll->compare($this->_Value, $obj->_Value);
 }
开发者ID:dazarobbo,项目名称:cola,代码行数:14,代码来源:MString.php

示例13: sortArray

 private function sortArray($results, $sortColumn, $collator = "en_US")
 {
     $rv = array();
     $i = 0;
     foreach ($results as $row) {
         $rv[] = $i++;
     }
     if ($sortColumn >= 0) {
         $c = new Collator($collator);
         $func = function ($a, $b) use($c, $results, $sortColumn) {
             return $c->compare($results[$a][$sortColumn], $results[$b][$sortColumn]);
         };
         usort($rv, $func);
     }
     return $rv;
 }
开发者ID:abassouk,项目名称:gss-spreadsheet-extractor,代码行数:16,代码来源:gss-spreadsheet-extractor.php

示例14: switch

 static function build_sorter_string($key, $order = 'DESC')
 {
     //setlocale(LC_COLLATE, 'fr_CA.utf8');
     switch ($order) {
         case 'DESC':
             return function ($a, $b) use($key) {
                 if (is_array($key)) {
                     $keyA = '';
                     $keyB = '';
                     foreach ($key as $value) {
                         $keyA .= $a[$value] . " ";
                         $keyB .= $b[$value] . " ";
                     }
                 } else {
                     $keyA = $a[$key];
                     $keyB = $b[$key];
                 }
                 $keyA = str_replace('/', ' ', $keyA);
                 $keyB = str_replace('/', ' ', $keyB);
                 $collator = new Collator("fr");
                 return $collator->compare($keyA, $keyB);
             };
             break;
         case 'ASC':
             return function ($a, $b) use($key) {
                 if (is_array($key)) {
                     $keyA = '';
                     $keyB = '';
                     foreach ($key as $value) {
                         $keyA .= $a[$value] . "/";
                         $keyB .= $b[$value] . "/";
                     }
                 } else {
                     $keyA = $a[$key];
                     $keyB = $b[$key];
                 }
                 $keyA = str_replace('/', ' ', $keyA);
                 $keyB = str_replace('/', ' ', $keyB);
                 $collator = new Collator("fr");
                 //$collator->setStrength(Collator::PRIMARY);
                 return !$collator->compare($keyA, $keyB);
             };
             break;
         default:
             return function ($a, $b) use($key) {
                 if (is_array($key)) {
                     $keyA = '';
                     $keyB = '';
                     foreach ($key as $value) {
                         $keyA .= $a[$value] . "/";
                         $keyB .= $b[$value] . "/";
                     }
                 } else {
                     $keyA = $a[$key];
                     $keyB = $b[$key];
                 }
                 $keyA = str_replace('/', ' ', $keyA);
                 $keyB = str_replace('/', ' ', $keyB);
                 $collator = new Collator("fr");
                 //$collator->setStrength(Collator::PRIMARY);
                 return $collator->compare($keyA, $keyB);
             };
             break;
     }
 }
开发者ID:nbtetreault,项目名称:igo,代码行数:65,代码来源:Utils.php

示例15: Collator

<?php

// Create a collator using Spanish locale
$collator = new Collator("es");
// Returns that the strings are equal, in spite of the emphasis on the "o"
$collator->setStrength(Collator::PRIMARY);
var_dump($collator->compare("una canción", "una cancion"));
// Returns that the strings are not equal
$collator->setStrength(Collator::DEFAULT_VALUE);
var_dump($collator->compare("una canción", "una cancion"));
开发者ID:aodkrisda,项目名称:phalcon-code,代码行数:10,代码来源:intl-81.php


注:本文中的Collator::compare方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。