开发者

top two elements of an associative array in php

I've accomplished the end goal for this already, but maybe there is a more elegant way of accomplishing this.

If I have an array like such:

$data = array(
    'wood' => 2,
    'metal' => 5,
    'plastic' => 3, 
);

I want to get the top 2 key/value pairs from $data (ie metal:5 & plastic:3). Here's what I came up with:

arsort($data);       //put values in order
reset($data);           //set pointer to first element
$first = each($开发者_JAVA百科data);    //assign first element to $first
array_shift($data); //remove first element from array
reset($data);           //set pointer to the new first element
$second = each($data); //assign the new first element to $second


For getting both key and value I would go this way:

arsort($data);
$result = array_slice($data,0,2);


asort($data);
$first = array_pop($data);
$second = array_pop($data);

Notice that instead of putting it in reverse order and grabbing the first items, I put it in order and grabbed the last items.


Your code is correct, you just have some extra calls there

arsort($data);
$first = each($data);
$second = each($data);

should be enough.

You need to be more specific though about what exactly you want to get. each returns an array of four elements - is this what you want?


Something like this:

$array = array (
    'wood'  => 2,
    'metal' => 1,
    'blah'  => 4
);

$first  = end($array);
$second = prev($array);


Maybe not exactly what a Priority Queue was intended for and regular array sorting and extracting functions are completely fine either, but to add something new:

$queue = new SplPriorityQueue;
$queue->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
$queue->insert('wood', 2);
$queue->insert('metal', 5);
$queue->insert('plastic', 3);

This is automatically sorted in descending order of the numeric value. To get the elements, do

var_dump(
    $queue->extract(),
    $queue->extract()
);

would give (codepad)

array(2) {  ["data"]=>  string(5) "metal",    ["priority"]=>  int(5) }
array(2) {  ["data"]=>  string(7) "plastic",  ["priority"]=>  int(3) }

and leaves $queue containing only 'wood' then.

In addition to the SplPriorityQueue, you could also use an SplMaxHeap.

Read more at:

  • Matthew Turland's Blog: New SPL Features in PHP 5.3 and
  • https://stackoverflow.com/questions/1957133/php-spl-reference-documentation/4218646#4218646
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜