我正在使用Lumen设置一个微服务,用于频繁轮询数据库,并通过wamp路由器将数据集分发给多个客户端。数据库查询存储在存储过程中,这就是为什么我在控制器中执行以下操作:
$result = DB::select($query);
return $result;
返回的数据集如下:
[
{
"0": "012345",
"1": "Moby Dick",
"2": "Herman Melville",
"3": "Hardcover",
"isbn": "012345",
"title": "Moby Dick",
"author": "Herman Melville",
"type": "Hardcover"
},
{
"0": "123456",
"1": "Laravel: Code Bright",
"2": "Dayle Rees",
"3": "Ebook",
"isbn": "123456",
"title": "Laravel: Code Bright",
"author": "Dayle Rees",
"type": "Ebook"
},
{
"0": "234567",
"1": "Easy Laravel 5",
"2": "W.J. Gilmore",
"3": "Ebook",
"isbn": "234567",
"title": "Easy Laravel 5",
"author": "W.J. Gilmore",
"type": "Ebook"
}
]
我想删除在关联键值对之前的数字键值对。我该怎么做?
提前感谢!
编辑:我尝试过的东西:
$result = DB::select($query)->get(); // Gives: Call to a member function get() on array. For obvious reasons
像Matei这样的肮脏黑客说:循环遍历数组并删除密钥为数字的KVP。这是有效的,但我认为Laravel/Lumen框架提供了更清洁的解决方案,这是我找不到的。
在config/database.php
中,您可以将'fetch' => PDO::FETCH_CLASS,
更改为'fetch' => PDO::FETCH_ASSOC,
或
你可以像一样使用array_reduce
和array_filter
$result = json_decode(DB::select($query), true);
$result = array_reduce($result, function ($result, $item) {
$result[] = array_filter($result, function ($key) {
return !is_numeric($key);
}, ARRAY_FILTER_USE_KEY)
return $result;
}, array());
return json_encode($result);
注意:如果DB stmt返回的是数组,而不是json编码的字符串,则必须删除json_decode
和json_encode
函数调用。