【问题标题】:Having some trouble with PHP usortPHP usort 遇到一些问题
【发布时间】:2018-06-06 12:12:34
【问题描述】:

我在使用 usort 订购的数组时遇到了一些问题。目前,它正在查看每个值的第一个数字并以此为基础进行排序,这很好,但这意味着我得到的是 - 1 街道 2 街道 3 街道,而不是 - 1 街道 10 街道 11街道。

我尝试添加 substr,但没有任何区别 - 我错过了什么?

function cmp($a, $b)
{
    return strcmp( substr( $a['0'], 0, 2 ), substr( $b['0'], 0, 2 ) );
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

...

usort($a, "cmp");

编辑

所以,我现在返回的数组如下所示:

[0] => Array
    (
        [0] => 1 The Street, The City, The County
        [1] => FriA
    )

[1] => Array
    (
        [0] => 10 The Street, The City, The County
        [1] => FriB
    )

[2] => Array
    (
        [0] => 11 The Street, The City, The County
        [1] => FriA
    )

第一个值是地址,第二个是时间表。 2 街道目前在 19 点之后显示,而不是 1 点。

function cmp( $a, $b ) {
    return strcmp( substr( $a[ '0' ], 0, 2 ), substr( $b[ '0' ], 0, 2 ) );
    if ( $a == $b ) {
        return 0;
    }
    return ( $a < $b ) ? -1 : 1;
}

foreach ( $json[ 'candidates' ] as $value ) {
    $address = $json[ 'candidates' ][ $index ][ 'attributes' ][ 'ADDRESS_1' ];
    $code = $json[ 'candidates' ][ $index ][ 'attributes' ][ 'CODE' ];
    $a[] = array( $address, $code );
    usort($a, "cmp");
    $index++;
}

echo '<pre>';print_r( $a );echo '</pre>';

【问题讨论】:

  • 您知道您的函数中只有第一行 (strcmp)...?
  • 你在函数中传递了什么?
  • 根据字符串比较显示结果是正确的...你必须比较数字比较.....
  • 很高兴您在这里展示了您尝试过的内容。现在请展示您的意见并说明您想要的结果。

标签: php arrays rest sorting substr


【解决方案1】:

根据您在此处更新的问题,建议。如果您的字符串总是以数字开头,您可以在 usort 中简单地转换为 int 并按如下方式排序:

usort($arr, function($a, $b) {
    return (int)$a[0] == (int)$b[0] ? 0 : ((int)$a[0] < (int)$b[0] ? -1 : 1);
});

php7 中的 spaceship operator 使 3 种方式的比较更加清晰:

usort($arr, function($a, $b) {
    return (int)$a[0] <=> (int)$b[0];
});

两者都做同样的事情 - 如果您使用的是 php7+,请使用后者。

【讨论】:

  • 感谢您的帮助,我确实尝试了 natsort 和 sort,但我得到的结果与上面相同。如果有帮助,我会在问题中添加更多信息
猜你喜欢
  • 2017-09-10
  • 1970-01-01
  • 2013-04-18
  • 2022-11-17
  • 2013-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
相关资源
最近更新 更多