问题描述
让S成为PHP中的关联数组,我需要从中检索并提取第一个元素(值和键).
Let S be an associative array in PHP, I need to retrieve and extract from it the first element, both the value and the key.
我会使用
value1=array_pop(S);
但这只会给我带来价值.
but it only gives me the value.
我可以使用
K=array_keys(S);
key1=array_pop(K);
value1=array_pop(S);
但是很复杂,因为它需要具有相同数据的两个副本.这是一个令人困惑的问题,因为数组本身就是数组数组中的一个元素.必须有一种更优雅的方法来在提取夫妇键/值的同时读取它.
but it is complicated because it requires to have two copies of the same data. WHich is a confusing since the array is itself an element in an array of arrays. There must be a more elegant way to just read the couple key/value while extracting it.
推荐答案
$value = reset($arr);
$key = key($arr);
(按此顺序)
unset($arr[$key]); # in case you want to remove it.
However array_pop()
is working with the last element:
$value = end($arr);
$key = key($arr);
unset($arr[$key]); # in case you want to remove it.
list($value, $key) = array(end($arr), key($arr));
或
extract(array('value'=>end($arr), 'key'=>key($arr)));
或
end($arr);
list($key, $value) = each($arr);
或您喜欢的任何游戏风格;)
or whatever style of play you like ;)
到目前为止,缺少处理空数组的方法.因此,需要检查是否存在最后一个(第一个)元素,如果没有,则将$key
设置为null
(因为null
不能是数组键):
It was missing so far to deal with empty arrays. So it's a need to check if there is a last (first) element and if not, set the $key
to null
(as null
can not be an array key):
for($key=null;$key===null&&false!==$value=end($arr);)
unset($arr[$key=key($arr)]);
这将提供一个像$arr = array('first' => '1st', 'last' => '2nd.');
这样的填充数组:
This will give for a filled array like $arr = array('first' => '1st', 'last' => '2nd.');
:
string(4) "2nd." # value
string(4) "last" # key
array(1) { # leftover array
["first"]=>
string(3) "1st"
}
还有一个空数组:
bool(false) # value
NULL # key
array(0) { # leftover array
}
是否害怕使用unset?
如果您不信任unset()
具有所需的性能(尽管我没有运行任何指标,但我不认为这确实是一个问题),可以使用本机array_pop()
实现也是如此(但我真的认为unset()
作为一种语言构造可能会更快):
Afraid of using unset?
In case you don't trust unset()
having the performance you need (of which I don't think it's really an issue, albeit I haven't run any metrics), you can use the native array_pop()
implementation as well (but I really think that unset()
as a language construct might be even faster):
end($arr);
$key = key($arr);
$value = array_pop($arr);
这篇关于弹出键PHP中关联数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!