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

标签 php arrays

是否可以在不先遍历数组的情况下设置 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/

相关文章:

php - 如何在拖放到 TinyMCE 时将 img 数据更改为 img url?

javascript - 使用附加属性创建数组

ios - 在 swift 4 中处理 JSON

php - 使用 session 登录

php - 在php中排序依赖子数组

php - SQL 树结构父子

java - 如何将两个大数相乘

javascript - jQuery AJAX : unexpected end of input

javascript - React JS 中的渲染没有返回任何内容

php - php中的支付api多维数组问题