我怎样才能在Laravel中使用array_where?

时间:2016-08-18 16:08:45

标签: php arrays laravel filter laravel-5.2

我有一个Eloquent查询返回的数组($payments),其中包含以下JSON编码输出:

[{"id":1, "user_id":"34","amount":"1000","status":"0","created_at":"2016-08-18 14:24:59","updated_at":"2016-08-18 14:24:59"},
{"id":3, "user_id":"33","amount":"300","status":"1","created_at":"2016-08-18 14:31:04","updated_at":"2016-08-18 14:33:20"},
{"id":4, "user_id":"33","amount":"1000","status":"0","created_at":"2016-08-18 14:31:27","updated_at":"2016-08-18 14:31:27"},
{"id":5, "user_id":"34","amount":"400","status":"1","created_at":"2016-08-18 14:42:02","updated_at":"2016-08-18 14:42:02"}]

我想在array_where()中使用Laravel方法并根据此条件过滤$paymentsstatus == 1,是否有人可以告诉我该怎么做?

3 个答案:

答案 0 :(得分:0)

您可能会惊讶地发现有一个名为array_filter的PHP函数正是这样做的。这是在行动

$array = [ ['id' => 1, 'status' => 0], ['id' => 2, 'status' => 1], ['id' => 3, 'status' => 0] ];

$array = array_filter($array, function ($item) {
    return $item['status'] == 1;
});

答案 1 :(得分:0)

如果这是Eloquent查询的结果,那么它不是数组,而是Collection。来自文档:

  

Eloquent返回的所有多结果集都是Illuminate\Database\Eloquent\Collection对象的实例

您可以使用Collection的filter方法,它接受一个闭包,并在闭包中返回您想要的条件('status' == 1)。

$filtered = $your_query_result->filter(function($value, $key) {
    return $value->status == 1;
});

答案 2 :(得分:0)

除非你调用toJson()方法,否则Eloquents结果默认不能是json。

为什么不添加到您的数据库查询条件?

示例:

$payments = Payment::where('status', '=', 1)->get(); // Payment is model
return response()->json($payments);

P.S。不建议从db获取大量的json数据,解析并过滤它 更好地利用数据库,不要让你的生活变得艰难(:

相关问题