sort array by sub array value

Thursday 26th July 2007 11:03 PM

TAGS: PHP, sort, array
I've come across this a few times in programming, the need to order an set of data by an array value inside it. A (very simple) example will make this clearer!

$dataSet = array(
  array('id' => 1'name' => 'Gavin'),
  array('id' => 2'name' => 'Frank'),
  array('id' => 3'name' => 'Bob'),
);
I want to keep my subsets of data "together". but order them by "name". There were a couple of solutions I saw, one of which using array_multisort, but they didn't -quite- get there in terms of what I needed, thus I came up with this small function, to re-order the data:
// sort an array by sub key
function sortArray($array$subValue)
{

    // create a temporary array of subkeys only
    foreach($array as $key => $value)
    $tempList[$key] = $value[$subValue];

    // sort temp array
    natsort($tempList);

    // merge the ordered list + old values
    foreach($tempList as $key => $value)
        $resultArray[$key] = $array[$key];

    // return resulting array
    return $resultArray;

}

$result sortArray($dataSet'name');
print_r($result);


Does anyone have a simpler or more efficient way to do this? Bearing in mind there could be more than one set of data, i would be interested to hear!

Comments on this article:


#1 Michael Leaney says:

Friday 27th July 2007 03:46 PM

array_multisort() should do the trick.

Part of this is straight from the manual.

The data as an array, called data. This would usually, for example, be obtained by looping with mysql_fetch_assoc().


In this example, we will order by volume descending, edition ascending.

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.



If we had more columns to sort by all we need to do is add them to the loop and function call. For Example:

Say there was another column titled pages, we would then use:
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
$pages[$key] = $row['key'];
}
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $pages, SORT_ASC, $data);


Add Comment:


Make a Comment

*Nb, all comments are moderated to prevent spam or inappropriate content.








netforge logo
netforge provides high quality and friendly website design services to business. We're Australian based and reliable... (find out more).