【问题标题】:Keeping array reference and adding something into that保持数组引用并在其中添加一些东西
【发布时间】:2021-09-02 01:45:09
【问题描述】:

在我非常简单的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);
    }
}

提前致谢

【问题讨论】:

  • 您的意思是要在现有数组中添加一个新的键值??
  • 您的点击处理程序称为add,但我在您的代码中没有看到add 函数。
  • @Peppermintology 很抱歉,我更新了帖子
  • @zahid hasan emon 是的,我想将新数据添加到现有数组中
  • 您能否提供一个您尝试添加到您的$productSizesdata 示例。

标签: php laravel laravel-livewire


【解决方案1】:

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

array_merge 将两个arrays 组合成一个array,而array_push 将元素添加到现有array

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

【讨论】:

  • 不工作,当我调用多个addNewSize 方法时。我有没有以前数据的新数组,我想将数据添加到现有数据的数组中
  • @DolDurma 那么你的代码中有一个错误,因为该原则确实有效
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2012-11-13
    • 2015-02-01
    • 2022-12-05
    相关资源
    最近更新 更多