【问题标题】:Insert multiple items in Laravel Collection inside a php loop在 php 循环内的 Laravel 集合中插入多个项目
【发布时间】:2021-11-20 03:18:50
【问题描述】:

您好,我正在尝试将多个项目插入 php 循环内的 laravel 集合中,但只有一个被插入(最后一个),请帮助插入所有值。

这个数组$some_array = array(); 的值类似于 1,2,3,4

循环就像

foreach ($some_array as $key => $value) {

                $final_lists = collect([
                    (object) [
                        'customer_id' => $value,
                    ],
                ]);
            }

需要输出

"final_lists": [
        {
            "customer_id": 4,
             "name": "Name 1",
        },
        {
            "customer_id": 2,
            "name": "Name 2",
        },
]

【问题讨论】:

  • 您可以使用 collect() (laravel.com/docs/8.x/collections#creating-collections)。只需使用collect(array)。你能分享一下需要的输出吗?
  • $final_lists->push('customer_id',$value);似乎正在添加,但结果不是集合而是关联数组
  • 为什么需要foreach 只需将$some_data 放入collect 函数$final_list = collect($some_array);
  • 在你上面的代码中。 collect() 帮助器/方法似乎每次在每个循环中都创建一个新的空集合,这就是为什么您只能看到集合中的最后一个元素的原因。在循环之前创建一个集合并继续在循环内的集合中插入值

标签: php laravel


【解决方案1】:

使用页面顶部的集合类.as,

use Illuminate\Support\Collection;
$collection = new Collection;

foreach([1,2,3,4] as $item) {
    $collection->push((object)[
        'customer_id' => $item,
        'name' => 'demostring'.$item
    ]);
}

dd($collection->all());

使用这个sn-p。让我知道结果。

【讨论】:

    【解决方案2】:

    如果您需要一个包含多个集合的列表,您可以将一个新集合附加到一个数组中,例如:

    $a = [1,2,3,4,5]; // Your Array
    $requiredList = [];
    foreach($a as $key => $value){
        $requiredList[] = (object)[
            'customer_id' => $value,
            'name' => 'Customer Name: ' . $value
        ];
    }
    dd($requiredList);
    

    它将提供所需的列表,例如:

    ^ array:5 [▼
      0 => {#3971 ▼
        +"customer_id": 1
        +"name": "Name1"
      }
      1 => {#3207 ▼
        +"customer_id": 2
        +"name": "Name2"
      }
      2 => {#3977 ▼
        +"customer_id": 3
        +"name": "Name3"
      }
      3 => {#3961 ▼
        +"customer_id": 4
        +"name": "Name4"
      }
      4 => {#3956 ▼
        +"customer_id": 5
        +"name": "Name5"
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 1970-01-01
      • 2014-09-29
      • 2019-08-14
      • 1970-01-01
      • 2021-10-30
      • 2015-03-16
      • 2019-04-13
      • 1970-01-01
      相关资源
      最近更新 更多