2014-11-10 4 views
1

Исходный массив состоит в следующем:ksort() производит, как неправильный результат

Array 
(
    [Danmark] => Country Object 
     (
      [id:protected] => 39 
      [name:protected] => Danmark 
      [code:protected] => DK 
      [stringIndex:protected] => DENMARK 
     ) 

    [Tyskland] => Country Object 
     (
      [id:protected] => 59 
      [name:protected] => Tyskland 
      [code:protected] => DE 
      [stringIndex:protected] => GERMANY 
     ) 

    [Irland] => Country Object 
     (
      [id:protected] => 78 
      [name:protected] => Irland 
      [code:protected] => IE 
      [stringIndex:protected] => IRELAND 
     ) 

    [Italien] => Country Object 
     (
      [id:protected] => 81 
      [name:protected] => Italien 
      [code:protected] => IT 
      [stringIndex:protected] => ITALY 
     ) 

    [Holland] => Country Object 
     (
      [id:protected] => 119 
      [name:protected] => Holland 
      [code:protected] => NL 
      [stringIndex:protected] => NETHERLANDS 
     ) 

    [Nya Zeeland] => Country Object 
     (
      [id:protected] => 122 
      [name:protected] => Nya Zeeland 
      [code:protected] => NZ 
      [stringIndex:protected] => NEW_ZEALAND 
     ) 

    [Polen] => Country Object 
     (
      [id:protected] => 138 
      [name:protected] => Polen 
      [code:protected] => PL 
      [stringIndex:protected] => POLAND 
     ) 

    [Spanien] => Country Object 
     (
      [id:protected] => 161 
      [name:protected] => Spanien 
      [code:protected] => ES 
      [stringIndex:protected] => SPAIN 
     ) 

    [Sverige] => Country Object 
     (
      [id:protected] => 166 
      [name:protected] => Sverige 
      [code:protected] => SE 
      [stringIndex:protected] => SWEDEN 
     ) 

    [Schweiz] => Country Object 
     (
      [id:protected] => 167 
      [name:protected] => Schweiz 
      [code:protected] => CH 
      [stringIndex:protected] => SWITZERLAND 
     ) 

    [England] => Country Object 
     (
      [id:protected] => 185 
      [name:protected] => England 
      [code:protected] => GB 
      [stringIndex:protected] => UNITED_KINGDOM 
     ) 

    [Osterrike] => Country Object 
     (
      [id:protected] => 197 
      [name:protected] => Osterrike 
      [code:protected] => AT 
      [stringIndex:protected] => AUSTRIA 
     ) 

    [Belgien] => Country Object 
     (
      [id:protected] => 236 
      [name:protected] => Belgien 
      [code:protected] => BE 
      [stringIndex:protected] => BELGIUM 
     ) 

) 

И после того, как я называю:

ksort($countries, SORT_STRING); 

я получаю это:

Array 
(
    [Osterrike] => Country Object 
     (
      [id:protected] => 197 
      [name:protected] => Osterrike 
      [code:protected] => AT 
      [stringIndex:protected] => AUSTRIA 
     ) 

    [Belgien] => Country Object 
     (
      [id:protected] => 236 
      [name:protected] => Belgien 
      [code:protected] => BE 
      [stringIndex:protected] => BELGIUM 
     ) 

    [Danmark] => Country Object 
     (
      [id:protected] => 39 
      [name:protected] => Danmark 
      [code:protected] => DK 
      [stringIndex:protected] => DENMARK 
     ) 

    [Tyskland] => Country Object 
     (
      [id:protected] => 59 
      [name:protected] => Tyskland 
      [code:protected] => DE 
      [stringIndex:protected] => GERMANY 
     ) 

    [Irland] => Country Object 
     (
      [id:protected] => 78 
      [name:protected] => Irland 
      [code:protected] => IE 
      [stringIndex:protected] => IRELAND 
     ) 

    [Italien] => Country Object 
     (
      [id:protected] => 81 
      [name:protected] => Italien 
      [code:protected] => IT 
      [stringIndex:protected] => ITALY 
     ) 

    [Holland] => Country Object 
     (
      [id:protected] => 119 
      [name:protected] => Holland 
      [code:protected] => NL 
      [stringIndex:protected] => NETHERLANDS 
     ) 

    [Nya Zeeland] => Country Object 
     (
      [id:protected] => 122 
      [name:protected] => Nya Zeeland 
      [code:protected] => NZ 
      [stringIndex:protected] => NEW_ZEALAND 
     ) 

    [Polen] => Country Object 
     (
      [id:protected] => 138 
      [name:protected] => Polen 
      [code:protected] => PL 
      [stringIndex:protected] => POLAND 
     ) 

    [Spanien] => Country Object 
     (
      [id:protected] => 161 
      [name:protected] => Spanien 
      [code:protected] => ES 
      [stringIndex:protected] => SPAIN 
     ) 

    [Sverige] => Country Object 
     (
      [id:protected] => 166 
      [name:protected] => Sverige 
      [code:protected] => SE 
      [stringIndex:protected] => SWEDEN 
     ) 

    [Schweiz] => Country Object 
     (
      [id:protected] => 167 
      [name:protected] => Schweiz 
      [code:protected] => CH 
      [stringIndex:protected] => SWITZERLAND 
     ) 

    [England] => Country Object 
     (
      [id:protected] => 185 
      [name:protected] => England 
      [code:protected] => GB 
      [stringIndex:protected] => UNITED_KINGDOM 
     ) 

) 

Когда я проверяю он с теми же индексами, но со значениями простых строк вместо моих объектов Country, он сортируется правильно. Когда я тестирую его с теми же индексами, но с пустыми объектами Test вместо объектов Country, он снова сортируется правильно. Но в этом конкретном случае он возвращает неверный результат. Они не сортируются никакими значениями внутри объекта, все значения кажутся случайными.

Country класс предельно прост:

class Country { 

    protected $id; 
    protected $name; 
    protected $code; 
    protected $stringIndex; 

} 

Что может по причине?

+1

Действительно ли это «Osterrike», или что-то вроде «Österrike»? Я не верю, что функции сортировки массива не знают обо всех юникодах. –

+0

Это 'Osterrike', потому что я удалил' Ö' для тестирования. Этот персонаж был моим первым подозрением. –

+0

Затем попробуйте вручную заменить версию umlauted равным ascii O и посмотреть, правильно ли она сортируется. Нет никакого способа, которым ksort потерпит неудачу по тексту ascii, но я поспорю, что вы блестящий пенни, он испортит версии с акцентом/юникодом. –

ответ

0

проводок как ответа, так как это будет очень некрасиво как комментарий:

Я не могу дублировать ваш O приходит первым:

код:

<?php 

$foo = array(
    'P' => 'regular p', 
    'Ö' => 'umlaut o', 
    'O' => 'regular o', 
    'A' => 'regular A' 
); 

var_dump ($ Foo); ksort ($ foo); var_dump ($ foo);

Результат:

array(4) { 
    ["P"]=> 
    string(9) "regular p" 
    ["Ö"]=> 
    string(8) "umlaut o" 
    ["O"]=> 
    string(9) "regular o" 
    ["A"]=> 
    string(9) "regular A" 
} 
array(4) { 
    ["A"]=> 
    string(9) "regular A" 
    ["O"]=> 
    string(9) "regular o" 
    ["P"]=> 
    string(9) "regular p" 
    ["Ö"]=> 
    string(8) "umlaut o" 
} 

Как вы можете видеть, Ö делает своего рода неправильно, но он сортирует до конца массива, а не начало.

+0

Удалось найти причину (комментарий в моем исходном сообщении). Это была моя ошибка. Извините и благодарю вас. –

-1

Мой ответ слишком поздно, я думаю, но, похоже, массив отсортирован по stringIndex полем объекта страны.

Может быть (только возможно, я не знаю точно) из-за SORT_STRING флага ksort пытается Fing элементов с определенным типом string, но если он не может, то он пытается найти ключи с «строкой» ключевое слово, подобное stringIndex Объект страны.