首页 > 解决方案 > 在循环中向数组添加值

问题描述

我正在开发一个 laravel 项目,该项目在满足某些条件时将值存储到循环中的数据库条目中。

如果条目是第一次,这首先会创建一个数组并向其添加一个值。此后,它会调用该数组并继续向其添加值。

if(is_null($lead->shown_to)) {
    $a = array();
    array_push($a, "lead 1");
    $lead->shown_to = serialize($cart);
    $lead->save();
} else {
    $a=unserialize($lead->shown_to);
    array_push($a, "lead 2");
    $lead->shown_to = serialize($a);
    $lead->save();
}

能够创建一个数组并向其中重复添加不同的元素。

有没有办法首先检查元素是否存在于其中。如果是,请继续前进,否则添加它?

提前致谢。

标签: phparrayslaraveleloquent

解决方案


在 Laravel 中,我会利用 Collections,因为它们有很多有用的方法可以使用。

我会做这样的事情:

选项1

//Depending on the value of $lead->show, initialize the cart variable with the serialization of the attribute or and empty array and transform it to a collection.

$cart = collect($lead->shown_to ? unserialize($lead->shown_to) : []);

//Ask if the collection doesn't have the given value. If so, added it.
if (!$cart->contains($your_value)) {
    $cart->push($your_value);
}

//Convert to array, serialize and store
$lead->shown_to = serialize($cart->toArray());
$lead->save();

选项 2

//Depending on the value of $lead->show, initialize the cart variable with the serialization of the attribute or and empty array and transform it to a collection.

$cart = collect($lead->shown_to ? unserialize($lead->shown_to) : []);

//Always push the value
$cart->push($your_value);

//Get the unique values, convert to an array, serialize and store
$lead->shown_to = serialize($cart->unique()->toArray());
$lead->save();

您可以使用这些集合获得更多创意,并且它们在 Laravel 上阅读得更好


推荐阅读