【发布时间】: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