David Bélanger
David Bélanger

Reputation: 7438

Sort multidimensional array who has index

I got an array like that

Array
(
    [0] => Array
    (
        [UnitESN] => 14296
        [ScanNo] => 1
        [ScanDate] => Nov 21
        [ScanTime] => 10:15 AM
        [Qualifiers] => 
        [Notes] => 
        [BadgeData] => Array
            (
                [0] => HEATH---
                [1] => MCCU----
                [2] => HER---
                [3] => HCONNORS@------
                [4] => 
                [5] => 393
                [6] => 13350
                [7] => 
                [8] => 
                [9] => 111
            )

        [Signal] => +00/000
        [ConnectionDelay] => 0407
    )

     [1] => Array

And so on... I want to order ASC or DESC... let's say on Col 8 and Col 8 is entry number 7 (8-1 because it start at zero) in BadgeData, any ideas ? I've try array_multisort but without succes.

Thanks

Upvotes: 0

Views: 133

Answers (2)

Francois Deschenes
Francois Deschenes

Reputation: 24989

I'm glad you figured it out. Here's what I started writing before I got interrupted.

Basic uasort Example:

<?php

function cmp($a, $b) {
    if ($a['BadgeData'][7] == $b['BadgeData'][7]) {
        return 0;
    }
    // Ascending
    return ($a['BadgeData'][7] < $b['BadgeData'][7]) ? -1 : 1;
}

// Order the values of the array based on the value in BadgeData[7] in ascending order..
uasort($array, 'cmp');

It looks like I may have misunderstood your original question though as I thought you wanted to sort the array by the value in BadgeData[7] but it seems like you wanted to sort the BadgeData for each array value.

Upvotes: 1

David B&#233;langer
David B&#233;langer

Reputation: 7438

Thanks to @Francois Deschenes to lead me on the right answer. Here's what I found :

https://www.php.net/manual/en/function.uasort.php#104714

I edited to fit my need. Thanks !

function SortArrayByCol(array $Array, $Key, $ASC=true, $Col=0) {
    $Result = array();

    $Values = array();
    foreach($Array as $ID => $Value){
        $Values[$ID] = isset($Value[$Key][$Col]) ? $Value[$Key][$Col] : null;
    }

    if($ASC){
        asort($Values);
    } else {
        arsort($Values);
    }

    foreach($Values as $Key => $Value) {
        $Result[$Key] = $Array[$Key];
    }

    return $Result;
}

Upvotes: 1

Related Questions