"_andrea.l" <an******************@libero.it> writes:
I'd like to roder an array:
$array[id][name]
$array[id][number]
$array[id][value]
I'd like to order $array by name or by numbre of by a
function($array[id1],$array[id2]) that return 1 or -1 if id1 is less tha
id2 or viceversa...
I assume "$array" is an array, and "id" refers to number indices.
Then you can sort using the "sort" method of arrays, which takes an
optional comparison function:
---
function cmpName(v1,v2) {
if (v1.name < v2.name) { return -1; }
else if (v1.name > v2.name) { return 1; }
else {return 0;}
}
$array.sort(cmpName); // now sorted by name
---
More generally, you can use these functions:
---
/* Compares anything that is recognized by "<" */
function cmp(v1,v2){
return (v2<v1)-(v1<v2); // tricky code, but it works
}
/* creates a function that compares objects by ther "propName" property */
function cmpProperty(propName) {
return function(v1,v2) {
return cmp(v1[propName],v2[propName]);
}
}
$array.sort(cmpProperty("name")); // sorted by name property
$array.sort(cmpProperty("number")); // sorted by number property
---
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'