TSU*_*SUK 6 php c php-extension
我开始编写一个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);
}
Run Code Online (Sandbox Code Playgroud)
PHP代码
<?php
$array1 = array(1,2,3,4);
$array2 = array(5,6,7,8);
echo '<pre>';
print_r(modarray($array1,$array2));
echo '</pre>';
?>
Run Code Online (Sandbox Code Playgroud)
PHP输出
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[1] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)
)
Run Code Online (Sandbox Code Playgroud)
有两种方法可以做到这一点,一种是使用迭代 API 完全“手动”:
\n\nHashPosition pos;\nzval *collection, **arg;\nuint hash_key_type;\nuint string_key_len;\nulong int_key;\nchar *string_key = NULL;\n\n... get the collection from somewhere, e.g. argument parsing ...\n\nwhile (!EG(exception) && zend_hash_get_current_data_ex(Z_ARRVAL_P(collection), (void **)&arg, &pos) == SUCCESS) {\n zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(collection), &pos);\n MAKE_STD_ZVAL(key);\n hash_key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(collection), &string_key, &string_key_len, &int_key, 0, &pos);\n\n // Invoke e.g. zend_hash_update\n\n zend_hash_move_forward_ex(Z_ARRVAL_P(collection), &pos);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n首选的替代方案是使用三个zend_hash_apply*()带有回调的函数,这被认为更优雅:
static int replace_value(zval **arg, zval ****params TSRMLS_DC)\n{\n add_next_index_zval(params, val);\n\n return ZEND_HASH_APPLY_REMOVE;\n}\n\nzval *in, ***out;\n... fill in from somewhere from somewhere, e.g. argument parsing ...\narray_init(**out);\nzend_hash_apply_with_argument(Z_ARRVAL_P(collection, (apply_func_arg_t) replace_value, params TSRMLS_CC);\nRun Code Online (Sandbox Code Playgroud)\n\n注意:我没有在本地测试这两个片段,而是从不同的地方复制了它。
\n| 归档时间: |
|
| 查看次数: |
559 次 |
| 最近记录: |