使用数字键对多维数组进行排序,但保持键相同只是更改顺序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用数字键对多维数组进行排序,但保持键相同只是更改顺序相关的知识,希望对你有一定的参考价值。
所以我有3维数组。我希望根据键重新排序该数组,但键的值应保持不变。就像一个例子,如果数组键是5,2,4,1,3那么它应该变成1,2,3,4,5。下面我提供了我拥有的阵列和排除阵列以及我尝试过的解决方案。
这是我的阵列: -
[5] => Array
(
[Anfield] => Array
(
[0] => Array
(
[slot] => E3
[deal_text] =>
[units] => 5
[total_units] => 5
[amount] => 2620.8333333333
[is_freezed] =>
[can_sell] => 1
)
)
)
[2] => Array
(
[Anfield] => Array
(
[0] => Array
(
[slot] => E4
[deal_text] =>
[units] => 1
[total_units] => 0
[amount] => 516.66666666667
[is_freezed] => 1
[can_sell] =>
)
)
)
[4] => Array
(
[Anfield] => Array
(
[0] => Array
(
[slot] => C8
[deal_text] =>
[units] => 1
[total_units] => 0
[amount] => 526.66666666667
[is_freezed] => 1
[can_sell] =>
)
)
)
[1] => Array
(
[Anfield] => Array
(
[0] => Array
(
[slot] => D4
[deal_text] =>
[units] => 1
[total_units] => 0
[amount] => 557.14285714286
[is_freezed] => 1
[can_sell] =>
)
)
)
[3] => Array
(
[Anfield] => Array
(
[0] => Array
(
[slot] => E5
[deal_text] =>
[units] => 1
[total_units] => 0
[amount] => 516.66666666667
[is_freezed] => 1
[can_sell] =>
)
)
)
以下是我尝试的解决方案: -
$result = ksort($result);
$result = array_values($result);
$result = array_splice($result, 0, 0);
$result = sort($result);
$result = array_splice($result, 0, count($result));
这是预期的数组: -
Array
(
[1] => Array
(
[Anfield] => Array
(
[0] => Array
(
[slot] => D4
[deal_text] =>
[units] => 1
[total_units] => 0
[amount] => 557.14285714286
[is_freezed] => 1
[can_sell] =>
)
)
)
[2] => Array
(
[Anfield] => Array
(
[0] => Array
(
[slot] => E4
[deal_text] =>
[units] => 1
[total_units] => 0
[amount] => 516.66666666667
[is_freezed] => 1
[can_sell] =>
)
)
)
[3] => Array
(
[Anfield] => Array
(
[0] => Array
(
[slot] => E5
[deal_text] =>
[units] => 1
[total_units] => 0
[amount] => 516.66666666667
[is_freezed] => 1
[can_sell] =>
)
)
)
[4] => Array
(
[Anfield] => Array
(
[0] => Array
(
[slot] => C8
[deal_text] =>
[units] => 1
[total_units] => 0
[amount] => 526.66666666667
[is_freezed] => 1
[can_sell] =>
)
)
)
[5] => Array
(
[Anfield] => Array
(
[0] => Array
(
[slot] => E3
[deal_text] =>
[units] => 5
[total_units] => 5
[amount] => 2620.8333333333
[is_freezed] =>
[can_sell] => 1
)
)
)
)
没有任何工作任何帮助将不胜感激。提前致谢。
答案
您正在使用
ksort
作为$result = ksort($result);
,ksort
返回TRUE / FALSE。这意味着你将它分配给$results
。在这里阅读PHP ksort
你的代码应该是: -
ksort($results);
代替
$result = ksort($result);
你可以使用ksort
进行密钥排序,这是一个例子
$arr = [
5 => [1,3],
3 => [2,3],
2 => [0,7]
];
ksort($arr);
echo '<pre>';
print_r($arr);
产量
Array
(
[2] => Array
(
[0] => 0
[1] => 7
)
[3] => Array
(
[0] => 2
[1] => 3
)
[5] => Array
(
[0] => 1
[1] => 3
)
)
以上是关于使用数字键对多维数组进行排序,但保持键相同只是更改顺序的主要内容,如果未能解决你的问题,请参考以下文章
PHP array_multisort—对多个数组或多维数组进行排序