gpt4 book ai didi

php - 设置内部数组指针而不在 PHP 中迭代

转载 作者:IT王子 更新时间:2023-10-29 00:12:10 25 4
gpt4 key购买 nike

是否可以在不先遍历数组的情况下设置 PHP 的内部数组指针。以下面的伪代码为例:

$array = range(1, 100);

// Represents the array key
$pointer = 66;

set_array_pointer($pointer, $array);

$nextValue = next($array); // Should return 68

最佳答案

LibertyPaul 使用 ArrayIterator::seek 提供的解决方案似乎是使 php 将指针设置为数组中某个位置而无需在用户空间中初始化循环的唯一方法。不过,php 将在内部循环遍历数组以设置指针,正如您可以从 php source 中读取的那样。 ArrayIterator::seek() 的:

/* {{{ 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);
} /* }}} */

所以看起来没有办法在不循环遍历数组的情况下将数组指针设置到某个位置

关于php - 设置内部数组指针而不在 PHP 中迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36719268/

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