我得到了一个键值数组,它表示要按组织层次结构(group
、unit
、department
、team
)筛选的选择,例如:
// dd($selections)
[
"group2" => [
"unit11" => [
"department50" => [
0 => "team10",
1 => "team58"
],
],
"unit10" => [],
],
"group5" => [
"unit23" => [
"department101" => []
],
],
]
它的结构稍有不同,其中每个键表示选择值,除了最后一个嵌套层,它是被选作值而不是键的team
的列表。
我需要基于这些选择构建查询以筛选出结果。对于上面的示例,查询类似于:
$fullQuery
->where(function($query) {
$query->where("group", "=", 'group2')
->where("unit", "=", 'unit11')
->where("department", "=", 'department50')
->where("team", "=", 'team10')
})
->orWhere(function($query) {
$query->where("group", "=", 'group2')
->where("unit", "=", 'unit11')
->where("department", "=", 'department50')
->where("team", "=", 'team58')
})
->orWhere(function($query) {
$query->where("group", "=", 'group5')
->where("unit", "=", 'unit23')
->where("department", "=", 'department101')
})
为此,我想以这样的方式“扁平化”数组,以便将所有唯一的结果作为数组:
arrays = [
['group' => 'group2', 'unit' => 'unit11', 'department' => 'department50', 'team' => 'team10'],
['group' => 'group2', 'unit' => 'unit11', 'department' => 'department50', 'team' => 'team58'],
['group' => 'group5', 'unit' => 'unit23', 'department' => 'department101'],
]
因为一旦我有了这些数组,我就可以迭代和查询它们:
$fullQuery = DB::table('mytable');
foreach ($arrays as $array) {
$fullQuery->orWhere(function($query) {
$query->where("group", "=", $array->group)
->where("unit", "=", $array->unit)
->where("department", "=", $array->department)
->where("team", "=", $array->team)
})
}
我试过用一些递归的方法,但是我不擅长递归,而且我离得到一个有效的结果还很远,除非有一种不使用递归的方法?
1条答案
按热度按时间tvmytwxo1#
接受了挑战把你打造成了一个
不要介意任意的
first
或$columns
数组,我必须把列名推到某个地方。你可以这样使用它
这是一个Demo of the function returns