【问题标题】:Sort data array structure in php for Czech language - correct sort of numbers在 php 中为捷克语排序数据数组结构 - 正确的数字排序
【发布时间】:2017-04-24 08:27:21
【问题描述】:

原问题:url

捷克语排序现在可以正常工作,但数字不能正常工作。例如对于这个数组:

$data = array(
 'items' => array(
    0 => array('city' => 'Praha 10'),
    1 => array('city' => 'Praha 2'),
    2 => array('city' => 'Praha 1'),
    3 => array('city' => 'Cheb'),
    4 => array('city' => 'České budějovice'),
    5 => array('city' => 'Šatov')
  ),
);



$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body, true )['data']['items'];
usort($data,
  function($a,$b) {
    $coll = collator_create( 'cs_CZ' );
    $aSortKey = collator_get_sort_key($coll, $a['city']);
    $bSortKey = collator_get_sort_key($coll, $b['city']);
    return $aSortKey >= $bSortKey;
  ;}
 );

结果将是:Cheb、České Budějovice、Praha 1、Praha 10、Praha 2、Šatov。

但正确的应该是:Cheb、České Budějovice、Praha 1、Praha 2、Praha 10、Šatov。

所以像 2 这样较小的数字必须在 10 或更高之前。

【问题讨论】:

  • 问题是你看到的不是数字。这些只是包含一些数字的字符串。如果您需要以数字方式排序,则需要提取数字并按它们排序。

标签: php arrays json sorting


【解决方案1】:

在 PHP 中,自然排序可以轻松处理这个问题:

这里是如何做到这一点的官方链接:php.net natural sort

标准排序:

Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

自然顺序排序:

Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

【讨论】:

  • 它不起作用,正如我从文档中看到的那样,无法在内部使用带有定义函数的 natsort。
【解决方案2】:

你试过natsort而不是你的选择吗?

【讨论】:

  • 它不起作用,正如我从文档中看到的那样,无法在内部使用带有定义函数的 natsort。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 2020-03-22
  • 1970-01-01
相关资源
最近更新 更多