I have an array in PHP and I need to sort by a nested array inside of the array...
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
$column - this is the the sortable 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]. My code doesn't work because its trying to sort an array not a value...
Thanks
CodePudding user response:
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);