asort sorting an array by subkeys and or node properties

Php, Divx, Apache, phpBB
Forum rules
Do not post any code that circumvents rules of any server. You are responsible for anything you use here.
Post Reply
darknkreepy3#
Site Admin
Posts: 253
Joined: Tue Oct 27, 2009 9:33 pm

asort sorting an array by subkeys and or node properties

Post by darknkreepy3# »

I was writing a simple events page in php with mysql and it dawned on my I was going to have to write an algorithm for sorting because my tables were named 'd20100924' as in d[year-month-day] so I split up the day and month with a substr for the areas i needed but the array had unsorted days if they were added randomly or worse, reverse order as most arrays input info anyway (logic).

here is a demo I wrote from another I found online with subkey sorting. It doesn't do too well on subkeys with the same values, i.e. two values with 'teacher' as 'kristoffe' but as long as your subkey values are unique, this is easy and perfect. I made the output echo to help you understand as clearly as possible what is going on.

Image

Code: Select all

<?php
/*
subKey_sort.php v1.0 by Kristoffe Brodeur. ©2010 All Rights Reserved.
09-24-2010
*/
$people=
    Array
        (
        '1x'=>Array('teacher'=>'kristoffe','class'=>'game design 101','month'=>'04'),
        '2c'=>Array('teacher'=>'genevieve','class'=>'anatomy 101','month'=>'01'),
        '3d'=>Array('teacher'=>'kelly ann','class'=>'hair design 101','month'=>'05'),
        '4g'=>Array('teacher'=>'antoine','class'=>'modeling 101','month'=>'03')
        );    
echo "<h4>multi-sort test</h4>";
//
function subval_sort($arrA,$subKey)
    {
    $arrB=Array();//copy subkeys for a simple asort
    $arrC=Array();//make a new array to take the b sort and move a nodes into c properly
    //
    foreach($arrA as $keyA=>$valA)
        {
        echo "$keyA:$valA =>".$subKey."[".$valA[$subKey]."] <br />";
        $arrB[$keyA]=$valA[$subKey];
        }
    echo "arrB<hr />";
    print_r($arrB);
    echo "<hr />";
    asort($arrB);
    echo "asort arrB<hr />";
    print_r($arrB);
    echo "<hr />";
    $lenB=count($arrB);
    //
    foreach($arrB as $keyT=>$valT)
        {
        echo "<h4>".$arrB[$keyT].":".$keyT."</h4>";
        }
    //
    foreach($arrB as $keyB=>$valB)
        {
        //$arrC[]=$arrA[$keyB];
        $arrC[$keyB]=$arrA[$keyB];
        }
    return $arrC;
    }
//-----
$people=subval_sort($people,'teacher');
print_r($people);
?>
Post Reply