php数组排序后保留键名,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');

标签:arrays,php

来源: https://codeday.me/bug/20191202/2086632.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值