简体   繁体   中英

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

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

http://ca2.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;
}

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.

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