0

I am having trouble on how can I get the result of the nested array, it shows only one data per Branch, it should be show all Division per Branch.

$selectedBranches = ['1', '5'];
$selectedDivisions = ['1', '3', '5', '26', '27'];

$branch = \App\Branch::whereIn('BranchID', $selectedBranches)->get();
$division = \App\Division::whereIn('DivisionID', $selectedDivisions)->get();

for ($b = 0; $b < count($selectedBranches); $b++) {
    for ($c = 0; $c < count($selectedDivisions); $c++) {
        if ($branch[$b]->BranchID == $division[$c]->BranchID) {
            $branch_arr[$branch[$b]->BranchID] = array(
                $division[$c]->DivisionName
            );
        }
    }
}

Branch Query Result

BranchID BranchName
1 BranchOne
5 BranchFive

Division Query Result

DivisionID DivisionName BranchID
1 Foo 1
3 Fooz 1
5 Rap 1
26 Bar 5
27 Barz 5

Output

^ array:2 [▼
  1 => array:1 [▶
    0 => "Foo"
  ]
  5 => array:1 [▶
    0 => "Bar"
  ]
]

Expected Output

^ array:5 [▼
  1 => array:1 [▶
    0 => "Foo",
    1 => "Fooz",
    2 => "Rap",
  ]
  5 => array:1 [▶
    0 => "Bar",
    1 => "Barz",
  ]
]
2
  • Can you print the result of the DB query? $branch = \App\Branch::whereIn('BranchID', $selectedBranches)->get(); $division = \App\Division::whereIn('DivisionID', $selectedDivisions)->get(); Oct 3, 2022 at 5:44
  • I just updated my post and added the result of each query. thanks
    – mj mj
    Oct 3, 2022 at 5:52

1 Answer 1

1
    $branch_arr = [];
    for ($b = 0; $b < count($selectedBranches); $b++) {
    $branch_arr[$branch[$b]['BranchID']] = [];
    for ($c = 0; $c < count($selectedDivisions); $c++) {
        if ($branch[$b]['BranchID'] == $division[$c]['BranchID']) {
            $branch_arr[$branch[$b]['BranchID']][] = array(
                $division[$c]['DivisionName']
            );
        }
    }
}
1
  • This answer is missing its educational explanation and therefore is missing an opportunity to educate/empower the asker and thousands of future researchers. Oct 13, 2022 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.