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(); Commented Oct 3, 2022 at 5:44
  • I just updated my post and added the result of each query. thanks Commented 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']
            );
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is missing its educational explanation and therefore is missing an opportunity to educate/empower the asker and thousands of future researchers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.