Php 具有数字和字母的多维数组排序
如何对多维数组排序。这就是我的数组的外观Php 具有数字和字母的多维数组排序,php,arrays,sorting,multidimensional-array,Php,Arrays,Sorting,Multidimensional Array,如何对多维数组排序。这就是我的数组的外观 [0] => Array ( [id] => 1 [title] => 3A [active] => 1 ) [1] => Array ( [id] => 1 [title] => A [active] => 1 ) [2] => Array ( [id] => 1
[0] => Array
(
[id] => 1
[title] => 3A
[active] => 1
)
[1] => Array
(
[id] => 1
[title] => A
[active] => 1
)
[2] => Array
(
[id] => 1
[title] => 2A
[active] => 1
)
[3] => Array
(
[id] => 1
[title] => B
[active] => 1
)
我尝试过几种usort方法,但似乎无法使其发挥作用。我需要对数组进行排序,以便它将按数字排序,然后按字母数字排序,如:A、B、2A、3A。
我不确定如果不添加一个position字段来指定标题的顺序,这是否可能,或者我在这里遗漏了什么?正如@Kargfen所说,您可以将usort与自定义函数一起使用。像这个:
usort($array, function(array $itemA, array $itemB) {
return myCustomCmp($itemA['title'], $itemB['title']);
});
function myCustomCmp($titleA, $titleB) {
$firstLetterA = substr($titleA, 0, 1);
$firstLetterB = substr($titleB, 0, 1);
//Compare letter with letter or number with number -> use classic sort
if((is_numeric($firstLetterA) && is_numeric($firstLetterB)) ||
(!is_numeric($firstLetterA) && !is_numeric($firstLetterB)) ||
($firstLetterA === $firstLetterB)
) {
return strcmp($firstLetterA, $firstLetterB);
}
//Letters first, numbers after
if(! is_numeric($firstLetterA)) {
return -1;
}
return 1;
}
此比较函数仅基于标题的第一个字母,但它可以完成此任务;-) 您可以在usort和自定义回调的帮助下解决该问题:
function customSort($a, $b)
{
if ($a['id'] == $b['id']) {
//if there is no number at the beginning of the title, I add '1' to temporary variable
$aTitle = is_numeric($a['title'][0]) ? $a['title'] : ('1' . $a['title']);
$bTitle = is_numeric($b['title'][0]) ? $b['title'] : ('1' . $b['title']);
if ($aTitle != $bTitle) {
return ($aTitle < $bTitle) ? -1 : 1;
}
return 0;
}
return ($a['id'] < $b['id']) ? -1 : 1;
}
usort($array, "customSort");
函数customSort($a,$b)
{
如果($a['id']=$b['id']){
//如果标题开头没有数字,我会将“1”添加到临时变量中
$aTitle=是数字($a['title'][0])?$a['title']:('1'.$a['title']);
$bTitle=是数字($b['title'][0])?$b['title']:('1'.$b['title']);
如果($aTitle!=$bTitle){
回报率($aTitle<$bTitle)?-1:1;
}
返回0;
}
回报($a['id']<$b['id'])?-1:1;
}
usort($array,“customSort”);
首先,函数比较“id”值,然后如果两项相等,则检查“title”值 您可以为每个项目构建一个“键”,其中数字部分在左边用0填充,这样,排序功能可以执行简单的字符串比较:
$temp = [];
foreach ($arr as $v) {
$key = sscanf($v['title'], '%d%s');
if (empty($key[0])) $key = [ 0, $v['title'] ];
$key = vsprintf("%06d%s", $key);
$temp[$key] = $v;
}
ksort($temp);
$result = array_values($temp);
此技术称为“.”排序不清楚。您想按数字ASC排序,然后按字母数字ASC排序?你的结果是2A,3A,A,B,所以。