Array (
[1090] => BENNETON
[6761] => BENNETON
[3963] => BENNETON
[1662] => BENNETON
[1099] => BENNETON
[694] => XELOLE
[2527] => XELOLE
[4553] => XELOLE
[7908] => XELOLE
[4787] => XELOLE
[8261] => GOLDEN
[8259] => GOLDEN
[8265] => GOLDEN
[2599] => VICTORYE
[860] => VICTORYE
[1117] => VICTORYE
[844] => VICTORYE
[2243] => MIMIC
[1035] => MIMIC
[1025] => MIMIC
[561] => MIMIC
[621] => MIMIC
[2404] => OPTIMUM
[2389] => OPTIMUM
[2396] => OPTIMUM
[1965] => OPTIMUM
[2403] => OPTIMUM 如何使所有具有值的元素都是MIMIC (和key),成为数组中的第一个元素,然后是所有带有GOLDEN的元素,然后是所有其他元素?
发布于 2020-12-29 03:45:42
您可以使用uasort实现自定义排序函数。像这样的东西会起作用的:
//$sortMe = your array
uasort($sortMe, function($a, $b){
if ($a === $b) { //if both values are the same
return 0; //don't change their position
}
if ($a === 'MIMIC' || $b === 'MIMIC') { //If either a or b are MIMIC (a and b can't both be MIMIC since that would have met our previous return condition
return $a === 'MIMIC' ? 1:-1; //If a is "MIMIC" it should be first, otherwise put b in front of a
}
if ($b === 'GOLDEN' || $b === 'GOLDEN') { //Do the same thing with GOLDEN (note, if either variable was "MIMIC" we would have already exited the function at this point
return $a === 'GOLDEN' ? 1:-1;
}
return 0; //Neither of our sort-words were found, don't change the order.
});
var_export($sortMe); //Will be sorted now.发布于 2020-12-31 08:25:38
来自手册array operators
+运算符返回追加到左侧数组的右侧数组;对于同时存在于两个数组中的键,将使用左侧数组中的元素,而忽略右侧数组中匹配的元素。
因此,您只需过滤掉form和mimics,然后形成过滤后的数组和原始数组的并集。
<?php
$items =[
'1090' => 'BENNETON',
'6761' => 'BENNETON',
'3963' => 'BENNETON',
'1662' => 'BENNETON',
'1099' => 'BENNETON',
'694' => 'XELOLE',
'2527' => 'XELOLE',
'4553' => 'XELOLE',
'7908' => 'XELOLE',
'4787' => 'XELOLE',
'8261' => 'GOLDEN',
'8259' => 'GOLDEN',
'8265' => 'GOLDEN',
'2599' => 'VICTORYE',
'860' => 'VICTORYE',
'1117' => 'VICTORYE',
'844' => 'VICTORYE',
'2243' => 'MIMIC',
'1035' => 'MIMIC',
'1025' => 'MIMIC',
'561' => 'MIMIC',
'621' => 'MIMIC',
'2404' => 'OPTIMUM',
'2389' => 'OPTIMUM',
'2396' => 'OPTIMUM',
'1965' => 'OPTIMUM',
'2403' => 'OPTIMUM'
];
$goldens = array_filter($items, function($v) { return $v == 'GOLDEN';});
$mimics = array_filter($items, function($v) { return $v == 'MIMIC';});
$result = $goldens + $mimics + $items;
var_export($result);输出:
array (
8261 => 'GOLDEN',
8259 => 'GOLDEN',
8265 => 'GOLDEN',
2243 => 'MIMIC',
1035 => 'MIMIC',
1025 => 'MIMIC',
561 => 'MIMIC',
621 => 'MIMIC',
1090 => 'BENNETON',
6761 => 'BENNETON',
3963 => 'BENNETON',
1662 => 'BENNETON',
1099 => 'BENNETON',
694 => 'XELOLE',
2527 => 'XELOLE',
4553 => 'XELOLE',
7908 => 'XELOLE',
4787 => 'XELOLE',
2599 => 'VICTORYE',
860 => 'VICTORYE',
1117 => 'VICTORYE',
844 => 'VICTORYE',
2404 => 'OPTIMUM',
2389 => 'OPTIMUM',
2396 => 'OPTIMUM',
1965 => 'OPTIMUM',
2403 => 'OPTIMUM',
)https://stackoverflow.com/questions/65482716
复制相似问题