<?php
/*
consider the order that 3 couples enter a restaurant
you could have the index of the array represent the order of entry
and each sub element represent the first name of each person in the couple
*/
function initialize_array( )
{
$array[0][] = 'james';
$array[0][] = 'jane';
$array[1] = array( "john" , "bobby");
$array[2][0] = 'helium';
$array[2][1] = 'nitrogen';
return $array;
}
$array = initialize_array( );
print "<pre>";
print "Assuming that the primary key for each subarray represents the timestamp of an event:";
print_r( $array );
sort( $array );
print "after a simple sort( array ) you'll notice the relationship between key and subarray values is lost: ";
print_r( $array );
print "\n<br />";
print "It is poor design to rely on the index as inherent information, better: ";
$betterarray[0] = array( '1' , 'james' , 'jane' );
$betterarray[1] = array( '2' , "john" , "bobby");
$betterarray[2] = array( '3' , "helium" , "nitrogen");
print_r( $betterarray );
print "James and Jane entered first, Bobby and john entered second, Helium & Nitrogen entered third, therefore even better:";
$betterarray[0] = array( "entry" => '1' , "husband" => 'james' , "wife" => 'jane' );
$betterarray[1] = array( "entry" => '2' , "husband" => "john" , "wife" => "bobby");
$betterarray[2] = array( "entry" => '3' , "husband" => "helium" , "wife" => "nitrogen");
print_r( $betterarray );
print "\n<br />";
print "the correctly organized data can have each column sorted:";
// Create 3 arrays to desgregate the lists of columns
foreach ( $betterarray as $key => $row) {
$entry[$key] = $row['entry'];
$husband[$key] = $row['husband'];
$wife[$key] = $row['wife'];
}
array_multisort( $entry, SORT_DESC, $husband, SORT_DESC, $wife, SORT_DESC, $betterarray);
print "array_multisort( \$entry, SORT_DESC, \$husband, SORT_DESC, \$wife, SORT_DESC, \$betterarray);";
print_r( $betterarray );
print "Add the original as the last parameter to sort by the common key";
array_multisort( $wife, SORT_ASC, $betterarray);
print "array_multisort( \$wife, SORT_ASC, \$betterarray);";
print_r( $betterarray );
print "\n<br />";
print 'foreach ( $betterarray as $key => $row) {' . "<br\>\n" ;
print ' $entry[$key] = $row["entry"];' . "<br\>\n";
print ' $husband[$key] = $row["husband"];' . "<br\>\n";
print ' $wife[$key] = $row["wife"]; }' . "<br\>\n";
print ' array_multisort( $entry, SORT_DESC, $husband, SORT_DESC, $wife, SORT_DESC, $betterarray);' . "<br\>\n";
print ' print_r( $betterarray ); ';
print "</pre>";
/*
function mycomparestring($a, $b)
{
return strcmp( $a[1], $b[1]);
}
usort( $betterarray , 'mycomparestring' );
print_r( $betterarray );
*/
?>