是否可以在不首先遍历数组的情况下设置PHP的内部数组指针。以下面的虚拟代码为例:
$array = range(1, 100);
// Represents the array key
$pointer = 66;
set_array_pointer($pointer, $array);
$nextValue = next($array); // Should return 68
答案 0 :(得分:10)
您可以使用ArrayObject
和ArrayIterator
:
$array = range(1, 100);
$pointer = 66;
$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();
$iterator->seek($pointer); //set position
$iterator->next(); // move iterator
$nextValue = $iterator->current();
答案 1 :(得分:9)
使用ArrayIterator::seek提供的解决方案LibertyPaul似乎是使php设置指向数组中位置的指针的唯一方法,而无需在userland中初始化循环。 然而,php将在内部循环遍历数组以设置指针,因为您可以从ArrayIterator :: seek()的php source中读取:
/* {{{ proto void ArrayIterator::seek(int $position)
Seek to position. */
SPL_METHOD(Array, seek)
{
zend_long opos, position;
zval *object = getThis();
spl_array_object *intern = Z_SPLARRAY_P(object);
HashTable *aht = spl_array_get_hash_table(intern);
int result;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &position) == FAILURE) {
return;
}
if (!aht) {
php_error_docref(NULL, E_NOTICE, "Array was modified outside object and is no longer an array");
return;
}
opos = position;
if (position >= 0) { /* negative values are not supported */
spl_array_rewind(intern);
result = SUCCESS;
while (position-- > 0 && (result = spl_array_next(intern)) == SUCCESS);
if (result == SUCCESS && zend_hash_has_more_elements_ex(aht, spl_array_get_pos_ptr(aht, intern)) == SUCCESS) {
return; /* ok */
}
}
zend_throw_exception_ex(spl_ce_OutOfBoundsException, 0, "Seek position %pd is out of range", opos);
} /* }}} */
所以看起来没有办法在不通过数组循环的情况下将数组指针设置到某个位置
答案 2 :(得分:2)
您可以使用next()和reset()来定义自己的函数以使用指针并使用如下代码
<?php
function findnext (&$array,$key) {
reset ($array);
while (key($array) !== $key) {
if (next($array) === false) throw new Exception('can not find key');
}
}
$array = range(1, 100);
$pointer = 66;
findnext($array,$pointer);
echo next($array); //this will give 68
?>
答案 3 :(得分:0)
您不需要为数组设置实际pointer
。 php
已经支持internal array pointers see next() method:
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = next($transport); // $mode = 'car';
$mode = prev($transport); // $mode = 'bike';
$mode = end($transport); // $mode = 'plane';