简体   繁体   中英

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...

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM