Search code examples
phparraysmultidimensional-arraynested-loops

PHP Creating Nested Array Dynamically


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",
  ]
]

Solution

  •     $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']
                );
            }
        }
    }