php 关联数组的前两个元素
我已经实现了最终目标,但也许有一种更优雅的方法来实现这一目标。
如果我有一个这样的数组:
$data = array(
'wood' => 2,
'metal' => 5,
'plastic' => 3,
);
我想从 $data 中获取前 2 个键/值对(即金属:5 和塑料:3)。这是我想出的:
arsort($data); //put values in order
reset($data); //set pointer to first element
$first = each($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
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($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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为了同时获得键和值,我会这样做:
For getting both key and value I would go this way:
请注意,我没有按相反顺序放置并抓取第一个项目,而是按顺序放置并抓取最后一个项目。
Notice that instead of putting it in reverse order and grabbing the first items, I put it in order and grabbed the last items.
您的代码是正确的,您只需进行一些额外的调用
就足够了。
你需要更具体地说明你到底想要得到什么。
each
返回一个由 四个 元素组成的数组 - 这是您想要的吗?Your code is correct, you just have some extra calls there
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:
也许不完全是优先级队列的用途和常规数组排序和提取函数也完全没问题,但要添加一些新内容:
这会自动按数值降序排序。要获取元素, do
会给出 (codepad)
并离开
$queue 则仅包含“木材”。
除了
SplPriorityQueue
之外,您还可以使用SplMaxHeap
。阅读更多信息:
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:
This is automatically sorted in descending order of the numeric value. To get the elements, do
would give (codepad)
and leaves
$queue
containing only 'wood' then.In addition to the
SplPriorityQueue
, you could also use anSplMaxHeap
.Read more at: