Re: retrieve top n entries from an associative array



No, it doesn't work since this function only works on indexed array.


Myron Turner wrote:
Below $a is an associative array. It is then sorted by value using
asort() and then its top ten elements are extracted using array_slice().
I think this is what you want?

Myron

<?php

$a = array( 'abc1' => 'apple',
'abc3' => 'angle',
'def' => 'dog' ,
'e' => 'egg',
'xyz' => 'word',
'm' => 'man',
'n' => 'nose',
'p' => 'pan',
'l' => 'lock',
'h' => 'head',
'c' => 'cook',
'g' => 'garden',
'f' => 'food'

);

asort($a);
echo "Associative Array Sorted By Value:\n";
print_r($a);

echo "Top ten elements:\n";
$top_ten = array_slice ( $a, 0, 10);
print_r ($top_ten);


/* Result:
Associative Array Sorted By Value:
Array
(
[abc3] => angle
[abc1] => apple
[c] => cook
[def] => dog
[e] => egg
[f] => food
[g] => garden
[h] => head
[l] => lock
[m] => man
[n] => nose
[p] => pan
[xyz] => word
)
Top ten elements:
Array
(
[abc3] => angle
[abc1] => apple
[c] => cook
[def] => dog
[e] => egg
[f] => food
[g] => garden
[h] => head
[l] => lock
[m] => man
)
*/
?>




duzhidian@xxxxxxxxx wrote:
Thanks for the replies. But both programs only meaningful for the
indexed array, not associative array.

I have no idea how to retrieve associative array according to the
length. Can you explain it?

--
Myron Turner wrote:
array array_slice ( array array, int offset [, int length])

<?php
$top_ten = array_slice ( $sorted, 0 , 10);

$a= array (1,2,3,4,5,6,7,8,9,10,11,12);
$top_ten = array_slice ( $a, 0, 10);
print_r ($top_ten);
?>

/* Result:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
*/


duzhidian@xxxxxxxxx wrote:
Hello,

After sorting an associative array by value, how can I retrieve top n
entries from it?

Thanks.

Zhidian Du


--

_____________________
Myron Turner
http://www.room535.org
http://www.bstatzero.org
http://www.mturner.org/XML_PullParser/



--

_____________________
Myron Turner
http://www.room535.org
http://www.bstatzero.org
http://www.mturner.org/XML_PullParser/

.