PHP   发布时间:2022-04-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了php-如何对数组执行自定义排序并保留键大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

所以我目前有这个:

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');

大佬总结

以上是大佬教程为你收集整理的php-如何对数组执行自定义排序并保留键全部内容,希望文章能够帮你解决php-如何对数组执行自定义排序并保留键所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: