[英]Sort multidimensional array by column value within a column
I have an array in PHP and I need to sort by a nested array inside of the array...我在 PHP 中有一个数组,我需要按数组内的嵌套数组进行排序...
Here is my array:这是我的数组:
Array
(
[0] => Array
(
[project_id] => 1
[earnest_money_due] => Array
(
[value] => 1000.00,
[currency] => 'USD'
)
)
[1] => Array
(
[project_id] => 2
[earnest_money_due] => Array
(
[value] => 200.00,
[currency] => 'USD'
)
)
[2] => Array
(
[project_id] => 3
[earnest_money_due] => Array
(
[value] => 900.00,
[currency] => 'USD'
)
)
Here's how I'm trying to sort it:这是我尝试对其进行排序的方式:
$records - this the array of records $records - 这是记录数组
$column - this is the the sortable column "earnest_money_due" $column - 这是可排序的列“earnest_money_due”
$columns = array_column($records, $column);
array_multisort($columns, SORT_ASC, $records);
I need to be able to sort by the [value] of the [earnest_money_due].我需要能够按 [earnest_money_due] 的 [value] 进行排序。 My code doesn't work because it's trying to sort an array, not a value.
我的代码不起作用,因为它试图对数组而不是值进行排序。
Try this...尝试这个...
<?php
$array = [
[
'project_id' => 1,
'earnest_money_due' => [
'value' => 1000.00,
'currency' => 'USD',
],
],
[
'project_id' => 2,
'earnest_money_due' => [
'value' => 200.00,
'currency' => 'USD',
],
],
[
'project_id' => 3,
'earnest_money_due' => [
'value' => 900.00,
'currency' => 'USD',
],
],
];
array_multisort(
array_map(
static function ($element) {
return $element['earnest_money_due']['value'];
},
$array
),
SORT_ASC,
$array
);
var_dump($array);
If you remove the SORT_ASC
, then your code works just fine.如果您删除
SORT_ASC
,那么您的代码就可以正常工作。 This is because PHP will sort your subarray as expected with it removed.这是因为 PHP 将按预期对您的子数组进行排序,并将其删除。 It will compare from the start of the subarray.
它将从子数组的开头进行比较。 ( Demo )
(演示)
array_multisort(array_column($array, 'earnest_money_due'), $array);
If that seems to hacky, unreliable, or unintuitive, array_map()
is fine.如果这看起来很老套、不可靠或不直观,
array_map()
就可以了。 ( Demo ) (演示)
array_multisort(array_map(fn($row) => $row['earnest_money_due']['value'], $array), $array);
There is also nothing wrong with using usort()
.使用
usort()
也没有错。 ( Demo ) (演示)
usort($array, fn($a, $b) => $a['earnest_money_due']['value'] <=> $b['earnest_money_due']['value']);
Regardless of which array_multsort()
technique you use, you don't need to explicitly use SORT_ASC
because this is the default sorting order.无论您使用哪种
array_multsort()
技术,您都不需要显式使用SORT_ASC
,因为这是默认排序顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.