使用PHP usort时遇到一些问题

使用PHP usort时遇到一些问题,php,arrays,rest,sorting,substr,Php,Arrays,Rest,Sorting,Substr,我在使用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; }

我在使用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");
第一个值是地址,第二个值是明细表。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>';
函数cmp($a,$b){
返回strcmp(substr($a['0'],0,2),substr($b['0'],0,2));
如果($a=$b){
返回0;
}
回报率($a<$b)?-1:1;
}
foreach($json['candidates']作为$value){
$address=$json['candidates'][$index]['attributes']['address_1'];
$code=$json['candidates'][$index]['attributes']['code'];
$a[]=数组($address,$code);
usort($a,“cmp”);
$index++;
}
回声';印刷费($a);回声';

根据您的最新问题,这里是您的建议。如果字符串总是以数字开头,则可以在usort内部将其转换为
int
,并按如下方式排序:

[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
    )
usort($arr, function($a, $b) {
    return (int)$a[0] <=> (int)$b[0];
});
usort($arr,function($a,$b){
返回值(int)$a[0]==(int)$b[0]?0:((int)$a[0]<(int)$b[0]?-1:1);
});
php7中的3种方式的比较更加清晰:

usort($arr,function($a,$b){
报税表(整数)$a[0](整数)$b[0];
});

这两个函数的作用相同-如果您使用的是php7+,请使用后者。

您知道,在函数中只有第一行(
strcmp
)会到达…?您在函数中传递的内容?根据字符串比较,显示结果是正确的。。。你必须比较数字比较……还有:你展示了你在这里尝试过的东西,这很好。现在请显示您的输入并说明您想要的结果。感谢您的帮助,我尝试了natsort和sort,但得到的结果与上面相同。如果有帮助的话,我已经在问题中添加了更多信息
usort($arr, function($a, $b) {
    return (int)$a[0] <=> (int)$b[0];
});