[英]Sort multidimensional array prioritising substring
I have a multi-dimensional array to work with and sort in PHP. 我有一个多维数组可以使用并在PHP中排序。 I am trying to sort it by the product_code key.
我正在尝试按product_code键对其进行排序。 The array needs to be arranged
阵列需要安排
Here is the array I have 这是我有的数组
Array
(
[0] => Array
(
[product_name] => Stellar
[product_code] => C5311.01
)
[1] => Array
(
[product_name] => Luigi
[product_code] => C5310.02
)
[2] => Array
(
[product_name] => Apple
[product_code] => C5310.01
)
[3] => Array
(
[product_name] => Quietly
[product_code] => C5311.02
)
)
This needs to be sorted as: 这需要分类为:
Array
(
[0] => Array
(
[product_name] => Apple
[product_code] => C5310.01
)
[1] => Array
(
[product_name] => Stellar
[product_code] => C5311.01
)
[2] => Array
(
[product_name] => Luigi
[product_code] => C5310.02
)
[3] => Array
(
[product_name] => Quietly
[product_code] => C5311.02
)
) )
I thought sorting the array by product_code key first and then by the substring using usort would yield me favourable results, but I was wrong. 我认为先按product_code键对数组进行排序,然后再使用usort对子字符串进行排序将为我带来令人满意的结果,但是我错了。 Maybe I am trying too hard..
也许我太努力了。
Any help would be highly appreciated. 任何帮助将不胜感激。 Thanks in advance.
提前致谢。
I think that usort
is actually what you need, but I think you are wrong in the way you are using it. 我认为
usort
实际上是您所需要的,但是我认为您使用它的方式是错误的。 If you need to sort 如果需要排序
- first in the ascending order of the last two characters of product_code
按product_code的最后两个字符的升序排列
- then in the ascending order of the characters preceding the '.'
然后以'。'前面的字符的升序排列。 of product_code
产品代码
just write a function which do this and pass it to usort
: 只需编写一个执行此操作的函数并将其传递给
usort
:
function cmp($a,$b){
$lastTwoDigitsCmp=strcmp(substr($a["product_code"], -2), substr($b["product_code"], -2));
if($lastTwoDigitsCmp==0)
return strcmp($a["product_code"],$b["product_code"]);
else
return $lastTwoDigitsCmp;
}
This should do the job. 这应该做的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.