重构嵌套的foreach循环

时间:2018-07-12 16:39:58

标签: php foreach refactoring

您能帮我重构这段代码吗?我很难决定如何重构每个循环的嵌套或完全不使用foreach循环。

$matcherResults = [];
foreach ($resultItems as $reqId => $resultItem) {
    if (empty($resultItem)) {
        continue;
    }

    foreach ($resultItem as $reg => $data) {
        if (empty($data)) {
            continue;
        }

        foreach ($data as $regs => $regData) {
            if (empty($regData)) {
                continue;
            }

            $matcherResult = new MatcherResult(
                $regData,
                null,
                $reg,
                $reqId
            );

            array_push($matcherResults, $matcherResult);

        }
    }
}

我尝试这样做,但是无法提出MatcherResult对象。

 foreach ($resultItems as $reqId => $resultItem) {
     $resultItem = array_filter($resultItem, function($resultItem) {
         if(!empty($resultItem)) {
             return true;
         }
     });
 }

 foreach ($resultItem as $regs => $value) {
     $matcherResults = array_filter($value, function($value) {
         return !empty($value);
     });    
 }

编辑: 按照要求。 这是resultItems的示例。

Array
    (
        [3] => Array
            (
                [test1] => Array
                    (
                        [0] => Array
                            (
                                [database] => test1
                                [active] => 1
                                [reg] => test1
                                [full_name] => fname1 lname1
                                [image_url] => image.png
                                [last_name] => lname1
                                [first_name] => fname1

                            )

                    )
            )
    )

1 个答案:

答案 0 :(得分:0)

较低的级别之一是否可能为空而不是空数组?如果为空只是检查一个空数组,则可以执行以下操作:

$matcherResults = [];
foreach ($resultItems as $reqId => $resultItem) {
    foreach ($resultItem as $reg => $data) {
        foreach ($data as $regs => $regData) {
            if (!empty($regData)) {
                $matcherResult = new MatcherResult(
                    $regData,
                    null,
                    $reg,
                    $reqId
                );
                array_push($matcherResults, $matcherResult);
            }
        }
    }
}