Ben Davidow
Ben Davidow

Reputation: 1215

Sort rows of a 2d array by a column's leading number so that odd numbers come before even numbers

I'm working with multi-dimensional arrays. Each array consists of properties along a street and one of the values is street address. I'd like to order the arrays such that all the odd addresses come before the even addresses. It's already ordered numerically (lowest to highest), so the only thing I'm trying to figure out is how to order the odds before the evens.

$array = [
    [
        'apn' => 345345345,
        'sqft' => 1200,
        'address' => '323 Pacific Ave.',
    ],
    [
        'apn' => 345345342,
        'sqft' => 1421,
        'address' => '324 Pacific Ave.',
    ],
    [
        'apn' => 345345346,
        'sqft' => 1001,
        'address' => '325 Pacific Ave.',
    ],
];

Upvotes: 1

Views: 50

Answers (2)

mickmackusa
mickmackusa

Reputation: 47904

usort() with odd checks in a descending order (odds = true are positioned first). Demo

usort(
    $array,
    fn($a, $b) => ((int)$b['address'] & 1) <=> ((int)$a['address'] & 1)
);
var_export($array);

Or use array_multisort() to perform fewer calculations. Demo

array_multisort(
    array_map(
        fn($v) => (int)$v['address'] & 1,
        $array
    ),
    SORT_DESC,
    $array
);
var_export($array);

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76656

Use usort() and define a custom sorting function:

usort($array, function($a, $b)
{
    if ($a['apn'] % 2 == $b['apn'] % 2) {
        if ($a['apn'] == $b['apn']) {
            return 0;
        }
        return ($a['apn'] < $b['apn']) ? -1 : 1;
    } 

    return ($a['apn'] % 2 == 0) ? 1 : -1;
});

Demo

Upvotes: 1

Related Questions