小事记-Github上提交的PR被官方合并,我成了80个贡献者之一

小事记-Github上提交的PR被官方合并,我成了ThinkPHP5.1,80个贡献者之一

使用ThinkPHP的数据验证类时,遇到了一个小bug,数字索引在数组合并时,有部分数据丢失,经过调试发现,是由于使用array_merge函数导致的,相关代码如下:

//@@ -187,7 +187,7 @@ class Validate
public function __construct(array $rules = [], array $message = [], array $field = [])
{
    $this->rule    = array_merge($this->rule, $rules);  /* 修改前 */
    $this->rule    = $rules + $this->rule;                /* 修改后 */
    $this->message = array_merge($this->message, $message);
    $this->field   = array_merge($this->field, $field);
}
//@@ -214,7 +214,7 @@ public static function make(array $rules = [], array $message = [], array $field
public function rule($name, $rule = '')
{
    if (is_array($name)) {
        $this->rule = array_merge($this->rule, $name);    /* 修改前 */
        $this->rule = $name + $this->rule;                /* 修改后 */
        if (is_array($rule)) {
            $this->field = array_merge($this->field, $rule);
        }
}

Google搜索了一番,其主要区别如下(引用自 PHP中array_merge函数与array+array的区别):

  1. 当下标为数值时,array_merge()不会覆盖掉原来的值,但array+array合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖).
  2. 当下标为字符时,array+array仍然把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉,但array_merge()此时会覆盖掉前面相同键名的值.

如果这段代码要验证的数组,Key是数值型时,使用array_merge会重建Key,导致之前的Key丢失,于是改用array + array的方式,对代码进行了如上的小修改,给ThinkPHP提交了一个Pull requests,第二天被合并,就这样成了ThinkPHP5.1的贡献者之一。