所以我目前有这个:
array(0=>'foo', 1=>'bar', 3=>'baz', 4=>'boo', 5=>'wahoo');
我想要的是:
array(0=>'foo', 3=>'baz', 1=>'bar', 5=>'wahoo', 4=>'boo');
这是一个简化的示例,我的实际数组更大,更复杂,因此不容易将其拆分成较小的块并重新组装.
我一直在使用uksort尝试这样做,我认为这是最好的方法,但似乎无法获得我想要的结果.
编辑:
我认为我的简化示例实际上使这个问题感到困惑.这是我的实际数组以及我最终想要得到的结果.
Array
(
[1820] => Safety
[1821] => Security
[1822] => Digital Life
[1893] => Privacy and Digital Footprints
[1823] => Connected Culture
[1824] => Respecting Creative Work
[1825] => Searching
[1826] => Research and Evaluation
[1836] => Self-Expression and Identity
)
Array
(
[1820] => Safety
[1821] => Security
[1822] => Digital Life
[1893] => Privacy and Digital Footprints
[1823] => Connected Culture
[1836] => Self-Expression and Identity
[1824] => Respecting Creative Work
[1825] => Searching
[1826] => Research and Evaluation
)
所以我几乎有一个数字排序,其中两个项目不按顺序进行.
解决方法:
基于讨论的新答案.
一定要使用uksort()
在比较功能中为匹配项进行切换并进行更改.
适用于以上示例的示例.
function updateKey($key)
{
switch($key)
{
case 1893:
return 1822.5;
case 1836:
return 1823.5;
default:
return $key;
}
}
function cmp($a, $b)
{
$a = updateKey($a);
$b = updateKey($b);
// you must do the compare this way for floats (instead of just subtracting) because php implemented the compare callback poorly
if ($a == $b)
{
return 0;
}
return ($a < $b) ? -1 : 1;
}
uksort($array, 'cmp');
标签:arrays,php
来源: https://codeday.me/bug/20191202/2086632.html