【发布时间】:2021-05-28 18:45:26
【问题描述】:
我正在寻找一种基于可变数量的排序键对多维数组进行排序的方法。
举个例子:
Array
(
[0] => Array
(
[userId] => 2
[amounts] => Array
(
[pencils] => 6
[phones] => 2
[watches] => 3
[balls] => 2
)
)
[1] => Array
(
[userId] => 1
[amounts] => Array
(
[pencils] => 6
[phones] => 3
[watches] => 4
[balls] => 1
)
)
[2] => Array
(
[userId] => 3
[amounts] => Array
(
[pencils] => 3
[phones] => 3
[watches] => 4
[balls] => 2
)
)
)
例如,我想先按电话对该数组进行排序,如果该值相同,则按手表,然后按球,然后按铅笔。
所以基本上,结果应该是:
Array
(
[0] => Array
(
[userId] => 3
[amounts] => Array
(
[pencils] => 3
[phones] => 3
[watches] => 4
[balls] => 2
)
)
[1] => Array
(
[userId] => 1
[amounts] => Array
(
[pencils] => 6
[phones] => 3
[watches] => 4
[balls] => 1
)
)
[2] => Array
(
[userId] => 2
[amounts] => Array
(
[pencils] => 6
[phones] => 2
[watches] => 3
[balls] => 2
)
)
)
现在,棘手的部分是在原始数组中,数量数组中的东西(例如铅笔、电话、手表、球)可以是可变的。因此,可能有 4 个类似示例,但也可能只有一个项目,或 5 个或...
我被分类弄湿了,尝试诸如
之类的东西usort($array, function($a, $b) {
return $a['amounts']['phones'] <=> $b['amounts']['watch'];
});
但我现在卡住了,不知道如何解锁自己。
非常感谢任何帮助!我正在使用 PHP 7。
更新:
根据 cmets 的要求,这是来自第一个数组的 var_export:
array (
0 =>
array (
'userId' => '2',
'amounts' =>
array (
'pencils' => '6',
'phones' => '2',
'watches' => '3',
'balls' => '2',
),
),
1 =>
array (
'userId' => '1',
'amounts' =>
array (
'pencils' => '6',
'phones' => '3',
'watches' => '4',
'balls' => '1',
),
),
2 =>
array (
'userId' => '3',
'amounts' =>
array (
'pencils' => '3',
'phones' => '3',
'watches' => '4',
'balls' => '2',
),
),
)
【问题讨论】:
-
所以如果它们是可变的。你有没有这个值按优先级排序的数组?
-
@nice_dev 是的,就是这样,只是一个简单的
array('phones','watches','balls','pencils'),其中顺序是优先级。 -
好的,你可以分享你的数组的 var_export() 吗?
-
我用请求的 var_export 更新了我的帖子。至于你的最后一个问题:那是不可能的。所有子数组将始终包含定义顺序的数组中定义的所有项(可能值为 0)。
-
所以它们是可变的,因为可以有 4 个(如示例中)或 3 或 7 个或任何值,但如果是例如 7 个,则所有子数组都将具有这 7 个项。
标签: php multidimensional-array