如何在不使用循环的情况下获取特定位置数组中第 n
个元素的 key
和 value
。
想象一下
$postion = 3; // get array at 3rd position
$array = array(
"A" => "Four",
"B" => "twp",
"C" => "three",
"D" => "Four",
"E" => "Five",
"F" => "Four");
$keys = array_keys($array);
$value = array_values($array);
echo implode(array_slice($keys, $postion, 1)), PHP_EOL; // Key at 3rd posstion
echo implode(array_slice($value, $postion, 1)), PHP_EOL; // Value at n position
输出
D
Four
该方法存在的问题是:
- 数组多次复制会导致内存使用量增加
为什么不使用循环?
- 您必须多次获取多个位置...循环大数据集也不高效
为什么不使用数据库?
- 是的,使用基于内存的数据库(如Redis)可以使生活更轻松,但我特别优化数组
为什么不使用SplFixedArray
?
This would have been solution but i the follow weer because am not using positive keys ( I really this is nor fair on php part)
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'array must contain only positive integer keys'
大数据集是什么意思:
- 实际上,当我尝试提出这个问题在PHP中管理超大数组时,我遇到了这个问题,所以我正在考虑使用
1e6
或1e7
和512M内存限制
我相信像fseek
这样的数组操作可以解决问题...但不确定是否存在
array_slice
而不是直接使用$keys[$position]
? - jeroen