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.
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);
?>