gpt4 book ai didi

php - php中关联数组的前两个元素

转载 作者:行者123 更新时间:2023-12-04 14:09:01 24 4
gpt4 key购买 nike

我已经完成了这个的最终目标,但也许有更优雅的方法来完成这个。

如果我有这样的数组:

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

我想从 $data 中获取前 2 个键/值对(即 metal:5 和 plastic: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

最佳答案

为了获得键和值,我会这样做:

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

关于php - php中关联数组的前两个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4445077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com