PHP7/5扩展开发函数手册(4) - 数组

数组 HashTable 获取

通过 Z_ARRVAL_P 来获取数组的 HashTable 数据结构

zset* zval;
HashTable *vht;
	
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &zset) == FAILURE)
{
    return;
}
	    
vht = Z_ARRVAL_P(zset);

根据 key 获取数组的 value

zend提供如下两个函数获取数组的 value

int zend_hash_find(HashTable *ht, char *arKey, uint nKeyLength,
void **pData);
int zend_hash_index_find(HashTable *ht, ulong h, void **pData);
第一种用来维护关联索引的数组, 第二种用于数字索引


在下面,我将 zend_hash_find 封装为 PHP5,和 PHP7 下的两个函数。

----php7_wrapper.h----

#if PHP_MAJOR_VERSION < 7 /* PHP Version 5*/
	static inline int sw_zend_hash_find(HashTable *ht, char *k, int len, void **v)
	{
	    zval **tmp = NULL;
	    if (zend_hash_find(ht, k, len, (void **) &tmp) == SUCCESS)
	    {
	        *v = *tmp;
	        return SUCCESS;
	    }
	    else
	    {
	        *v = NULL;
	        return FAILURE;
	    }
	}
#else /* PHP Version 7 */
	static inline int sw_zend_hash_find(HashTable *ht, char *k, int len, void **v)
	{
	    zval *value = zend_hash_str_find(ht, k, len - 1);
	    if (value == NULL)
	    {
	        return FAILURE;
	    }
	    else
	    {
	        *v = (void *) value;
	        return SUCCESS;
	    }
	}
#endif /* PHP Version */

#define php_swoole_array_get_value(ht, str, v)	(sw_zend_hash_find(ht, str, sizeof(str), (void **) &v) == SUCCESS && !ZVAL_IS_NULL(v)) //根据 key 获取数组 value

----test.c----

PHP_METHOD(get_array_value_by_key)
{
	zval *zset;
	HashTable *vht;
	zval *v;
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &zset) == FAILURE)
    {
        return;
    }
    
    vht = Z_ARRVAL_P(zset);
    
	//process_num
	if (php_swoole_array_get_value(vht, "process_num", v))
	{
		php_var_dump(v);
	}
    
    RETURN_TRUE;
}

猜你喜欢

转载自blog.csdn.net/caohao0591/article/details/82191001