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

A

_andrea.l

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.
 
R

Richard Cornford

_andrea.l said:
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.
 
L

Lasse Reichstein Nielsen

_andrea.l said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top