laravel 如何将此关联数组转换为包含键的分隔数组,但最后一个嵌套级别包含值

pn9klfpd  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(101)

我得到了一个键值数组,它表示要按组织层次结构(groupunitdepartmentteam)筛选的选择,例如:

// 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)
    })
}

我试过用一些递归的方法,但是我不擅长递归,而且我离得到一个有效的结果还很远,除非有一种不使用递归的方法?

tvmytwxo

tvmytwxo1#

接受了挑战把你打造成了一个

function queryBuilder($input, $column, &$finalArray, &$buildUpArray = [])
{
    $columns = ['first' => 'group', 'group' => 'unit', 'unit' => 'department', 'department' => 'team'];
    if(!isset($columns[$column])) {
        return;
    }
    $column = $columns[$column];
    foreach ($input as $key => $item) {
        $tempArray = $buildUpArray;
        if (!is_array($item) || !$item) {
            $tempArray[$column] = !$item ? $key : $item;
            $finalArray[] = $tempArray;
        } else {
            $tempArray[$column] = $key;
            queryBuilder($item, $column,$finalArray, $tempArray);
        }
    }
}

不要介意任意的first$columns数组,我必须把列名推到某个地方。
你可以这样使用它

$filters = [];
queryBuilder($inputs, 'first', $filters);

foreach ($filters as $filter) {
    $query->orWhere($filter);
}

这是一个Demo of the function returns

相关问题