php三数排列代码,按优先级排列的PHP排序数组

我需要一个按优先级排序项目数组的方法。

以下是迄今为止我所做的工作:

function arraySortPriority(array &$array, $offset, array $priorities)

{

uasort($array, function ($a, $b) use ($offset, $priorities) {

if (!isset($a[$offset])) {

$a[$offset] = null;

}

if (!isset($b[$offset])) {

$b[$offset] = null;

}

if ($a[$offset] == $b[$offset]) {

return 0;

}

$aPriority = isset($priorities[$a[$offset]])

? $priorities[$a[$offset]]

: null;

$bPriority = isset($priorities[$b[$offset]])

? $priorities[$b[$offset]]

: null;

return $aPriority > $bPriority ? -1 : 1;

});

}

// an array to sort

$array = [

['type' => 'A'],

['type' => 'A'],

['type' => 'B'],

['type' => 'B'],

['type' => 'C'],

['type' => 'C'],

['type' => 'D'],

['type' => 'D'],

['type' => 'E'],

['type' => 'E'],

['type' => 'F'],

['type' => 'F'],

['type' => 'G'],

['type' => 'G'],

['type' => 'H'],

['type' => 'H'],

['type' => 'Foo'],

['type' => 'Foo'],

['type' => 'Bar'],

['type' => 'Bar'],

[0 => 'no type should be last'],

[0 => 'no type should be last'],

];

// shuffle the array

shuffle($array);

// set priorities

$priorities = [

'A' => 8,

'B' => 7,

'C' => 6,

'D' => 5,

'E' => 4,

'F' => 3,

'G' => 2,

'H' => 1,

];

// call

arraySortPriority($array, 'type', $priorities);

// test output

foreach ($array as $item) {

if (isset($item['type'])) {

echo "{$item['type']}\r\n";

} else {

$values = array_values($item);

echo reset($values) . PHP_EOL;

}

}

预期:

A

A

B

B

C

C

D

D

E

E

F

F

G

G

H

H

Foo

Foo

Bar

Bar

no type should be last

no type should be last

实际:

A

A

B

B

C

C

D

D

E

E

F

F

G

G

H

H

no type should be last

no type should be last

Bar

Bar

Foo

Foo

问题是,未提供的项

$offset

应始终按底部排序。

这意味着

no type should be last

排序应始终低于

Foo

Bar

.

我该怎么做?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值