php - 在循环中向数组添加值
问题描述
我正在开发一个 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();
}
能够创建一个数组并向其中重复添加不同的元素。
有没有办法首先检查元素是否存在于其中。如果是,请继续前进,否则添加它?
提前致谢。
解决方案
在 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 上阅读得更好
推荐阅读
- php - PHP中多维数组的输出
- python - 您能否将 tf.keras.applications 中的预制模型用于一维时间序列数据?
- amazon-web-services - 如何在 Python Chalice 中创建 API 网关和 SQS 之间的直接集成
- python - 如何在并行化函数中将几何图形添加到地理数据框中?
- postgresql - 根据postgrersql中的列数据变化创建一个过程
- php - 由于某种原因,CSV 导入用 NULL 填充记录
- function - 仅使用 map 函数找出两个列表是否有一些共同的元素
- javascript - videojs - 如何仅使特定时间窗口处于活动状态?
- html - 背景图片渐变应该和文字一样长
- json - jQgrid没有在loadComplete上加载自定义userData