Home > front end >  Sort multidimensional array by column value within a column
Sort multidimensional array by column value within a column

Time:05-13

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 it's trying to sort an array, not a value.

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);

CodePudding user response:

If you remove the SORT_ASC, then your code works just fine. This is because PHP will sort your subarray as expected with it removed. 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. (Demo)

array_multisort(array_map(fn($row) => $row['earnest_money_due']['value'], $array), $array);

There is also nothing wrong with using 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.

  • Related