469,900 Members | 1,485 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,900 developers. It's quick & easy.

how to order an array by a particular rule or a function?

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...
How can I do that?
How can I order in a complex case like this?
Thank you in advance,
Andrea.
Jul 23 '05 #1
2 1256
_andrea.l wrote:
I'd like to roder an array:
$array[id][name]
$array[id][number]
$array[id][value]
Is this an array? How is it created, and its values assigned?
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...
What are id1 and id2, and in what sense do they have magnitudes?
How can I do that?
You have not provided sufficient information to have that question
answered.
How can I order in a complex case like this?

<snip>

Nothing presented so far suggest a complex case here.

Richard.
Jul 23 '05 #2
"_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.'
Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.