首页 > 解决方案 > Laravel 使用点符号合并两个数组

问题描述

我认为我的大脑今天无法正常工作,因为我似乎无法理解这个问题。

我有一个具有数据数组的类,例如 -

class Testing {

    protected $fillable = ['questions.*.checked'];

    protected $data = [
        'active' => true,
        'questions' => [
            [
                'question' => 'This is the first question',
                'checked' => true,
            ],
            [
                'question' => 'This is the second question',
                'checked' => false,
            ]
         ]
    ];

    public function fill(array $attributes = []) {
        // take our attributes array, check if the key exists in
        // fillable, and if it does then populate our $data property
    }

}

我想做的是,如果我将以下数组传递给该Testing::fill()方法,它只会更新被认为是可填充的相应属性。

例如,传递以下数组

[
    'active' => false,
    'questions' => [
        [
            'question' => 'This is the first question',
            'checked' => true,
        ],
        [
            'question' => 'This is the second question',
            'checked' => true,
        ]
    ]
]

只会修改对象上的选中标志,其他所有内容都将被忽略 - 仅将属性 $data 属性标记questions.*.checked为 true

我觉得有一个使用 Laravel 助手的解决方案,但我似乎无法解决,或者我可能走错了路......

最终,我只想要某种程度的清理,这样当整个结构被发送回对象填充方法时,实际上只有某些项目可以得到更新(就像 Laravel 的填充方法一样,只是更深入地使用动态值)。问题是 $data 中实际包含的内容是动态的,所以可能有一个问题,可能有 100 个......

标签: arrayslaravel-5.7

解决方案


好的,我想出了一个可以完成这项工作的解决方案,但我希望那里有一些更以 Laravel 为中心的东西。


protected function isFillable($key)
{
    // loop through our objects fillables
    foreach ($this->fillable as $fillable) {

        // determine if we have a match
        if ($fillable === $key
            || preg_match('/' . str_replace('*', '([0-9A-Z]+)', $fillable) . '/i', $key)
        ) {
            return true;
        }
    }

    // return false by default
    return false;
}

public function fill(array $attributes = [])
{
    // convert our attributes to dot notation
    $attributes = Arr::dot($attributes);

    // loop through each attribute
    foreach ($attributes as $key => $value) {

        // check our attribute is fillable and already exists...
        if ($this->isFillable($key)
            && !(Arr::get($this->data, $key, 'void') === 'void')
        ) {

            // set our attribute against our data
            Arr::set($this->data, $key, $value);
        }
    }

    // return ourself
    return $this;
}

因此,在上面,当我调用 fill() 方法时,我使用 . 将所有属性转换为 Laravel 的点符号Arr::dot()。这使数组更容易循环并允许我执行我正在寻找的那种检查。

然后我创建了一个isFillable()方法来确定 attributes 键是否存在于我们的 objects$fillable属性中。如果涉及通配符,它​​将星号 (*) 转换为正则表达式,然后检查是否存在匹配项。在执行正则表达式之前,它会执行基本的比较检查,理想情况下希望绕过正则表达式并尽可能提高整体性能。

所以,最后,如果我们的属性是可填充的,并且我们已经能够从我们的数据数组中获取值,那么我们将让这个值更新使用Arr::set()


推荐阅读