PHP排序 - 得到10,11,12 ... 1,20,2而不是1,10,11,12 ... 2,20

时间:2014-08-15 15:21:39

标签: php sorting amazon-mws

我有这样的参数需要排序(注意:我在将key =>值组合转换为字符串后进行排序):

$param['SignatureMethod']  = 'HmacSHA256';  
$param['SignatureVersion'] = '2'; 
$param['Timestamp']        = gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
$param['Version']          = '2011-10-01'; 
$param['SellerSKUList.SellerSKU.1']    = $sku1;
$param['SellerSKUList.SellerSKU.2']    = $sku2;
$param['SellerSKUList.SellerSKU.3']    = $sku3;
$param['SellerSKUList.SellerSKU.4']    = $sku4;

我总共有30个参数。为了调用端点,我需要按字母顺序生成参数的签名。

使用PHP的sort()可以正常工作少于10,但是当我尝试使用20时,它会给我这样的输出:

SellerSKUList.SellerSKU.10=4574&
SellerSKUList.SellerSKU.11=4575&
...
SellerSKUList.SellerSKU.18=4582&
SellerSKUList.SellerSKU.19=4583&
SellerSKUList.SellerSKU.1=4565&
SellerSKUList.SellerSKU.20=4584&
SellerSKUList.SellerSKU.2=4566

我需要它像这样:

SellerSKUList.SellerSKU.1=4565&
SellerSKUList.SellerSKU.10=4574&
SellerSKUList.SellerSKU.11=4575&
...
SellerSKUList.SellerSKU.18=4582&
SellerSKUList.SellerSKU.19=4583&
SellerSKUList.SellerSKU.2=4566&
SellerSKUList.SellerSKU.20=4584

排序功能如下所示:

$url = array();
foreach ($param as $key => $val) {

    $key = str_replace("%7E", "~", rawurlencode($key));
    $val = str_replace("%7E", "~", rawurlencode($val));
    $url[] = "{$key}={$val}";
}

sort($url);

在我看来,sort()函数应该提供所需的输出,但我的经验表明不同。是否有另一种函数或其他方法在字符串中对10之前的1进行排序?

我试过了:

usort($url,strcmp)  => 10,11,12...1,20,2
uksort($url,strcmp) => 10,11,12...20,2,1
natsort($url)       => 1,2,3,...10,11,12

Desired:            => 1,10,11...19,2,20

1 个答案:

答案 0 :(得分:1)

我找到了一个解决方案 - 如果我在插入key =>值对之前uksort($params,strcmp),则排序顺序正确。

uksort($param, 'strcmp');

$url = array();
foreach ($param as $key => $val) {

    $key = str_replace("%7E", "~", rawurlencode($key));
    $val = str_replace("%7E", "~", rawurlencode($val));
    $url[] = "{$key}={$val}";
}

感谢@Thomas Smart的评论:https://stackoverflow.com/a/12505517/2661831

我仍然想知道是否有办法对这样的字符串进行排序:

SellerSKUList.SellerSKU.10=4574&
SellerSKUList.SellerSKU.11=4575&
SellerSKUList.SellerSKU.18=4582&
SellerSKUList.SellerSKU.19=4583&
SellerSKUList.SellerSKU.1=4565&
SellerSKUList.SellerSKU.20=4584&
SellerSKUList.SellerSKU.2=4566