使用php扩展实现一个红包函数
如何开发及使用扩展
参考:https://www.jianshu.com/p/24fb7885361a
红包扩展函数
PHP_FUNCTION(get_random_money)
{
zend_long money, num;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &money, &num) == FAILURE) {
RETURN_FALSE;
}
if (money < num)
{
RETURN_FALSE;
}
zend_long money_arr[num];
zend_long rem = money % num;
zend_long mean = (money - rem) / num;
int r1, r2, mon;
double per;
for (int i = 0; i < num; i++) {
money_arr[i] = mean;
}
money_arr[0] = money_arr[0] + rem;
for (int i = 0; i < num; i++) {
r1 = rand() % num;
r2 = rand() % num;
per = (double) (rand() % 99) / 100;
mon = money_arr[r1] - floor(money_arr[r1] * per);
if (money_arr[r1] - mon > 0) {
money_arr[r1] = money_arr[r1] - mon;
money_arr[r2] = money_arr[r2] + mon;
}
}
array_init(return_value);
for (int i = 0; i < num; i++) {
add_next_index_long(return_value, money_arr[i]);
}
return;
}
调用红包函数
<?php
// 给20个人发红包
$monerys = get_random_money(1000, 20);
// 打印红包
var_dump($monerys);
// 统计总金额
var_dump(array_sum($monerys));
网友评论