Solved

# Sorting an array by a key value..

Posted on 2008-11-07
Medium Priority
424 Views
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
Question by:graphxdiva
1 Comment

LVL 82

Accepted Solution

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

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