lime icon

Phosphorus and Lime

A Developer's Broadsheet

This blog has been deprecated. Please visit my new blog at klenwell.com/press.
PHP: sort array by one field in array
There's probably a PHP function that does this, but I haven't been able to find it, so I rolled my own. First procedurally:

# ingredients
# $ARRAY : array or arrays to be sorted
# $sortby_index : index/column to be sorted on
# $key_index : equivalent to primary key column in SQL array

# get ordering array
foreach ( $ARRAY as $_DATA )
{
$_key = $_DATA[$key_index];
$ORDERING[$_key] = $_DATA[$sortby_index];
}

# sort ordering array
asort($ORDERING);

# DEBUG
#trigger_notice($ORDERING);

# map ARRAY back to ordering array
foreach ( $ORDERING as $_key => $_sort_col_val )
{
# get index for ARRAY where ARRAY[][$key_index] == $_key
foreach ($ARRAY as $_i => $_DATA)
{
if ( $_key == $_DATA[$key_index] )
{
$SORTED[] = $ARRAY[$_i];
continue;
}
}
}


Now as a function

function sort_array_of_arrays($ARRAY, $sortby_index, $key_index)
{
// *** NOTES
/*
requires array of associative arrays -- not checked within array
*/

// *** DATA

# order array
$ORDERING = array();

# return
$SORTED = array();

# internal
$_DATA = array();
$_key = '';
$_sort_col_val = '';
$_i = 0;


// *** MANIPULATE

# get ordering array
foreach ( $ARRAY as $_DATA )
{
$_key = $_DATA[$key_index];
$ORDERING[$_key] = $_DATA[$sortby_index];
}

# sort ordering array
asort($ORDERING);

# DEBUG
#trigger_notice($ORDERING);

# map ARRAY back to ordering array
foreach ( $ORDERING as $_key => $_sort_col_val )
{
# get index for ARRAY where ARRAY[][$key_index] == $_key
foreach ($ARRAY as $_i => $_DATA)
{
if ( $_key == $_DATA[$key_index] )
{
$SORTED[] = $ARRAY[$_i];
continue;
}
}
}

// *** RETURN

return $SORTED;

} # end Fx


Assumes asort will sort matters for you. Function will not work if you have to do some calculations on the sort index before sorting. But easily adapted.

keywords: PHP, array, sort
Holy crap it works. Thanks a lot, I really needed this just at this moment.