Php 调用另一个中间的方法防止设置下列变量- Laravel作业
我有一个Laravel作业,它设置一些数据,然后使用这些数据在数据库中创建一个条目。数据库表中的所有字段均为空。有一个Php 调用另一个中间的方法防止设置下列变量- Laravel作业,php,laravel,laravel-5.4,Php,Laravel,Laravel 5.4,我有一个Laravel作业,它设置一些数据,然后使用这些数据在数据库中创建一个条目。数据库表中的所有字段均为空。有一个custom\u变量字段-使用自定义方法getByPrefix()设置 MyJob.php <?php class MyJob implements ShouldQueue { public function __construct($input) { $this->input = $input; } public fun
custom\u变量
字段-使用自定义方法getByPrefix()
设置
MyJob.php
<?php
class MyJob implements ShouldQueue {
public function __construct($input) {
$this->input = $input;
}
public function handle() {
$data = $this->getData();
MyModel::create($data);
}
protected function getData() {
if (isset($this->input['name'])) {
$data['name'] = $this->input['name'];
}
$data['custom_variables'] = $this->getByPrefix('custom-');
if (isset($this->input['surname'])) {
$data['surname'] = $this->input['surname'];
}
return $data;
}
/**
* Filter the input by the provided prefix
* and return matching input data.
* @return null|string
*/
protected function getByPrefix($prefix) {
$this->input= array_filter($this->input, function($k) use ($prefix) {
return strpos($k, $prefix) !== false;
}, ARRAY_FILTER_USE_KEY);
if (count($this->input) === 0) {
return null;
}
$data = array();
foreach ($this->inputas $k => $v) {
array_push($data, array($k => $v));
}
if (empty($data)) {
return null;
}
return json_encode($data);
}
输出(应用getByPrefix()
后):
正是因为这一部分:
$this->input= array_filter($this->input, function($k) use ($prefix) {
return strpos($k, $prefix) !== false;
}, ARRAY_FILTER_USE_KEY);
您正在筛选输入并将结果覆盖到其中。尝试使用另一个变量
$input= array_filter($this->input, function($k) use ($prefix) {
return strpos($k, $prefix) !== false;
}, ARRAY_FILTER_USE_KEY);
您得到的是
name
而不是name
的原因很简单,因为您在调用方法之前设置了name,而在调用方法之后设置了name。显示$data@delboy1978uk更新了帖子。是的,我刚想出来。尽管如此,您花费的时间比我少10倍:)调试其他代码更容易。。。不要忘记在…之后立即在foreach中更改变量。。。
$this->input= array_filter($this->input, function($k) use ($prefix) {
return strpos($k, $prefix) !== false;
}, ARRAY_FILTER_USE_KEY);
$input= array_filter($this->input, function($k) use ($prefix) {
return strpos($k, $prefix) !== false;
}, ARRAY_FILTER_USE_KEY);