# Array

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
•  Array
• news.inet.tele.dk
• 11-25-2005
Hi
Can you help me sort my array on salary

\$Person[\$personid][salary]

e.g.
\$Person[1][20000]
\$Person[2][5000]
\$Person[3][15000]
\$Person[4][10000]

to
\$Person[2][5000]
\$Person[4][10000]
\$Person[3][15000]
\$Person[1][20000]

Thanx

## Re: Array

news.inet.tele.dk wrote:

http://php.net/usort 2nd example.

--
E. Dronkert

## Re: Array

Care to show how?

## Re: Array

Joe wrote:

Yes topposter: exactly according to example no. 2 on http://php.net/usort

--
E. Dronkert

## Re: Array

As I see it it can sort the values but doesn't keep the personid fixed to
the salary.

## Re: Array

Joe wrote:

Is that important? I don't know. I mean, where's the real data? He only
showed us the keys of a 2D array. Very weird to use salary as the 2nd key!
And, is there only one index value for each personid??

So, use uasort instead of usort:

function cmp(\$a, \$b) {
list(\$k1,) = each(\$a);
list(\$k2,) = each(\$b);
return \$k1 - \$k2;
}
uasort(\$person, 'cmp');

Or:

\$k = array_keys(\$person);
foreach ( \$k as \$i )
list(\$salary[\$i],) = each(\$person[\$i]);
asort(\$salary);

--
E. Dronkert

## Re: Array

Ewoud Dronkert wrote:

One salary figure, I mean. It do seems likely to have only one salary per
person, also the sorting wouldn't make sense otherwise.

A far better data structure would probably be, in pseudo code:
\$person[] = array('id' => (int), 'name' => (string), 'salary' => (float));

Then the solution would be:

function cmp(\$a, \$b) {
return \$a['salary'] - \$b['salary'];
}

Or a little safer:

function cmp(\$a, \$b) {
\$e = 0.01;
\$t = \$a['salary'] - \$b['salary'];
if ( \$t >= \$e ) return 1;
if ( \$t <= -\$e ) return -1;
return 0;
}

Followed by:

usort(\$person, 'cmp');
foreach ( \$person as \$p )
printf('%3d %-20s %8.2f', \$p['id'], \$p['name'], \$p['salary']);

--
E. Dronkert

## Re: Array

That worked perfect, thank you very much.

Next problem is for me to calculate:
Total and avg. value of the 25 highest paid workers
Total and avg. value of the 50 highest paid workers
I can do it by looping through the array, is there a way to do it in one
command?