获取元素,N位置在没有循环数组 [英] Get Element at N position in an Array without Loop
问题描述
如何让你获得元素键
和值
的在 N
在没有环特定位置的位置数组。
How get you get element key
and value
of an at the n
position array at a particular position without loop.
想象
$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
-
这将是解决办法,但我是因为我没有使用积极的键后续weer(我真的这也不公平PHP的一部分)
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'
你说的大数据集的意思是:
What do you mean by large data set :
- Actually i stumble on this issue when trying to as this question Managing mega Arrays in PHP so am looking at
1e6
or1e7
with512M memory limit
我相信像 fseek的
不知道是否存在
Am sure something like fseek
for array would do the trick .. but not sure if that exists
推荐答案
假设PHP 5.4,用数组语法:
Assuming PHP 5.4, with array dereferencing:
echo $array[array_keys($array)[$position]];
在你需要把它分解成两行较早版本:
In earlier versions you need to break it into two lines:
$keys = array_keys($array);
echo $array[$keys[$position]];
这也将是值得一用两行方式在5.4+,如果您有访问多个元素,让你只能叫相对昂贵 array_keys()
函数一次。另外,间接引用方法假设数组中的特定位置的存在,这也可能不是。分解成多个业务将允许您处理的错误情况。
It would also be worth using the two-line approach in 5.4+ if you have to access multiple elements, to allow you to only call the relatively expensive array_keys()
function once. Also the dereferencing approach assumes that the specific position within the array exists, which it may not. Breaking it into multiple operations would allow you to handle that error case.
虽然当然,你永远不要需要访问键,你可以简单地做:
Although of course you don't ever need access to the key, you can simply do:
echo array_values($array)[$position];
// or
$values = array_values($array);
echo $values[$position];
修改
ArrayIterator
类可以也为你做这个:
The ArrayIterator
class can also do this for you:
$iterator = new ArrayIterator($array);
$iterator->seek($position);
echo $iterator->key(), " = ", $iterator->current(); // D = Four
这可能是最便宜的方式做到这一点假设,当你这样做(仍在研究这个元素),它不会在内存中创建数组的副本,并有可能对任意键的多个访问的最佳方法。
This is probably the least expensive way to do this assuming it doesn't create a copy of the array in memory when you do it (still researching this element), and likely the best method for multiple accesses of arbitrary keys.
这篇关于获取元素,N位置在没有循环数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!