保留数组引用并向其中添加一些内容

Keeping array reference and adding something into that

在我非常简单的 Laravel livewire 组件中,我有一个数组,当我尝试通过单击一个简单的示例向其中添加另一个数据时 div 我得到了包含最后插入数据的新数组进入那个,我不能保留这个数组引用来将一些数据附加到那个

<div wire:click="addNewSize"></div>
class SellerStoreNewProductComponent extends Component
{
    public array $productSizes=[];
    
    //...

    public function addNewSize()
    {
        /* SOLUTION ONE */
        //$this->productSizes[] = $this->productSizes + [str::random(10) => str::random(10)];

        /* SOLUTION TWO */
        //$this->productSizes[][]=array_push($this->productSizes, [str::random(10) => str::random(10)]);

        /* SOLUTION THREE */
        //array_push($this->productSizes, [str::random(10) => str::random(10)]);

        dd($this->productSizes);
    }
}

提前致谢

您当前的方法将使用新数组数据(先前值加上新值)添加新索引。所以你只需要向数组添加新索引。

$this->productSizes['myKey'] = "myValue";

如果您希望将 key value 对添加到现有数组,您很可能希望使用 array_merge rather than array_push.

array_merge 将两个 arrays 组合成一个 arrayarray_push 将元素添加到现有的 array.

public function addNewSize()
{
    $this->productSizes = array_merge(
        $this->productSizes, [Str::random(10) => Str::random(10)]
    );
}