?
Solved

Sorting an array by a key value..

Posted on 2008-11-07
3
Medium Priority
?
424 Views
Last Modified: 2013-12-13
I am having some trouble sorting an array into the order that I want..  It looks like this..

$results = array();
$results[0] = array (
"table"=>"String",
"total"=>"String",
"data"=>array ("some", "data", "for", "multidimensional array");,
"distance"=>44 );

$results[1] = array (
"table"=>"String",
"total"=>"String",
"data"=>array ("some", "data", "for", "multidimensional array");,
"distance"=>30 );

$results[2] = array (
"table"=>"String",
"total"=>"String",
"data"=>array ("some", "data", "for", "multidimensional array");,
"distance"=>40 );

I would like the array to be sorted by distance, shortest to longest.  How can I go about ding that?

Thanks for any help!
0
Comment
Question by:graphxdiva
1 Comment
 
LVL 82

Accepted Solution

by:
hielo earned 2000 total points
ID: 22907957
try:
<?php
function cmp($a, $b)
{
    return strcmp($a["distance"], $b["distance"]);
}
$results = array();
$results[0] = array (
"table"=>"String",
"total"=>"String",
"data"=>array ("some", "data", "for", "multidimensional array");,
"distance"=>44 );

$results[1] = array (
"table"=>"String",
"total"=>"String",
"data"=>array ("some", "data", "for", "multidimensional array");,
"distance"=>30 );

$results[2] = array (
"table"=>"String",
"total"=>"String",
"data"=>array ("some", "data", "for", "multidimensional array");,
"distance"=>40 );


usort($results, "cmp");

...
?>
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses
Course of the Month17 days, 11 hours left to enroll

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question