Solved

sort a multi dimensional array

Posted on 2003-12-09
7
240 Views
Last Modified: 2011-08-18
If made a multiple dimension array which looks like this:

$result[$i] = array('type' => 'pagina', 'id' => $row['id'], 'titel' => $row['titel'], 'intro' => $row['intro'], 'score' => $row['score']);

now I would like to sort it on score (highest on top).

array_multisort() claims it can do this, but i don't understand this function ( http://www.php.net/manual/nl/function.array-multisort.php ) So maybe someone can tell me how the code should look like..

Emiel
0
Comment
Question by:EmielElgersma
  • 2
7 Comments
 
LVL 3

Accepted Solution

by:
red010knight earned 20 total points
ID: 9906340
From the looks of it you are pulling this from a database. If that is the case, the database call should be able to sort the data for you.

In MySQL the Query would be:
$sqlQuery="SELECT * FROM test SORT BY score DESC";

as to the way you sort... Multisort should be avoided. As it is complex and rather crazy.
If you are just sorting by one field... you should be able to do sort($result[$i]['score']); I think, or just write a quick bubble sort that would look something like:
<?php
// init var
$RESSIZE = sizeof($result ) ;
$i=0;
$aux=0;
$change = true;

// the sort
while( $i<$RESSIZE-1):
   $j=0;
   while( $j < $RESSIZE):
       if( $arr[$i] < $arr[$j] ):
           $aux = $arr[$i];
           $arr[$i] = $arr[$j];
           $arr[$j] = $aux;
       endif;
       $j++;
       endwhile;
   $i++;
endwhile;
?>
0
 
LVL 33

Expert Comment

by:snoyes_jw
ID: 9906605
red010knight is right if you are using a db query - much easier to let the db sort for you.

The array_multisort syntax would be:
$sortedArray = array_multisort($result['score'], $result['type'], $result['id'], $result['titel'], $result['intro']);

This will sort by score, then type, then id, then titel (sic), then intro.
0
 
LVL 33

Expert Comment

by:snoyes_jw
ID: 10106794
It's been a while since the last post.  Is the problem solved?
0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 10307057
Here's a GREAT sorting function that I just got from the comments in the array_multisort help page:

-----------------------------------------------------
function array_csort() {  //coded by Ichier2003
   $args = func_get_args();
   $marray = array_shift($args);

   $msortline = "return(array_multisort(";
   foreach ($args as $arg) {
       $i++;
       if (is_string($arg)) {
           foreach ($marray as $row) {
               $sortarr[$i][] = $row[$arg];
           }
       } else {
           $sortarr[$i] = $arg;
       }
       $msortline .= "\$sortarr[".$i."],";
   }
   $msortline .= "\$marray));";

   eval($msortline);
   return $marray;
}
-----------------------------------------------------

It's EXTREMELY easy to use and very scalable - I just incorporated into a project no less than a few minutes ago (I found this while searching for help on the same subject).

Let's say I have an array that looks like this:

$MDArray[] = array("Name" => "Product 1", "Features" => "5", "Price" => "10.00");
$MDArray[] = array("Name" => "Product 2", "Features" => "5",  "Price" => "25.00");
$MDArray[] = array("Name" => "Product 3", "Features" => "6",  "Price" => "50.00");
$MDArray[] = array("Name" => "Product 4", "Features" => "7",  "Price" => "100.00");

I could easily sort this by either Name, Features, or Price. To sort by ascending price, for example:
$MDArray = array_csort($MDArray, "Price", SORT_ASC);

To sort by most expensive first:
$MDArray = array_csort($MDArray, "Price", SORT_DESC);

Or to sort by most features first and then by cheapest price:
$MDArray = array_csort($MDArray, "Features", SORT_DESC, "Price", SORT_ASC);

This is a great tool. Thanks Ichier.

- Jonathan
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

910 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now