gpt4 book ai didi

PHP 扩展遍历数组

转载 作者:可可西里 更新时间:2023-11-01 13:30:29 26 4
gpt4 key购买 nike

我正开始编写一个 PHP 扩展,并希望了解如何循环遍历传递的数组(目的是逐个更改数据值)。首选方法是 for 循环,以便我可以将 array1 与 array2 数据匹配,例如array1[0] 链接到 array2[0],[1] 和 [1] 等...

有人能帮忙吗?

modarray.c

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"

extern zend_module_entry modarray_module_entry;
#define phpext_modarray_ptr &modarray_module_entry

PHP_FUNCTION(modarray);

static function_entry modarray_functions[] = {
PHP_FE(modarray, NULL)
PHP_FE_END
};

zend_module_entry modarray_module_entry = {
STANDARD_MODULE_HEADER,
"modarray",
modarray_functions,
NULL,
NULL,
NULL,
NULL,
NULL,
"0.1",
STANDARD_MODULE_PROPERTIES
};

ZEND_GET_MODULE(modarray)

PHP_FUNCTION(modarray)
{
zval *val, *val2;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &val, &val2) == FAILURE){
return;
}

SEPARATE_ZVAL(&val);
SEPARATE_ZVAL(&val2);

array_init(return_value);

zval_add_ref(&val);
zval_add_ref(&val2);
add_next_index_zval(return_value, val);
add_next_index_zval(return_value, val2);
}

PHP 代码

<?php
$array1 = array(1,2,3,4);
$array2 = array(5,6,7,8);
echo '<pre>';
print_r(modarray($array1,$array2));
echo '</pre>';
?>

PHP 输出

Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)

[1] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)

)

最佳答案

有两种方法可以做到这一点,一种是使用迭代 API 完全“手动”:

HashPosition pos;
zval *collection, **arg;
uint hash_key_type;
uint string_key_len;
ulong int_key;
char *string_key = NULL;

... get the collection from somewhere, e.g. argument parsing ...

while (!EG(exception) && zend_hash_get_current_data_ex(Z_ARRVAL_P(collection), (void **)&arg, &pos) == SUCCESS) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(collection), &pos);
MAKE_STD_ZVAL(key);
hash_key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(collection), &string_key, &string_key_len, &int_key, 0, &pos);

// Invoke e.g. zend_hash_update

zend_hash_move_forward_ex(Z_ARRVAL_P(collection), &pos);
}

首选的替代方法是使用三个带有回调的 zend_hash_apply*() 函数之一,这被认为更优雅:

static int replace_value(zval **arg, zval ****params TSRMLS_DC)
{
add_next_index_zval(params, val);

return ZEND_HASH_APPLY_REMOVE;
}

zval *in, ***out;
... fill in from somewhere from somewhere, e.g. argument parsing ...
array_init(**out);
zend_hash_apply_with_argument(Z_ARRVAL_P(collection, (apply_func_arg_t) replace_value, params TSRMLS_CC);

注意:我没有在本地测试任何一个片段,而是从不同的地方复制的。

关于PHP 扩展遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24556641/

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