I have following 2 tables with following values:
tbl_brand
id name
<
While you can generate the desired array in a single loop, I would rather execute two queries. First fetch all brands into an array and add an empty products array to every brand. Then fetch all products and assign them to the related brand.
Since I don't know what DB library you are using, here some kind of pseudo code:
$data = [];
$brandResult = $db->query("SELECT id, name FROM tbl_brand");
while ($row = $brandResult->fetchObject()) {
$row->product_names = [];
$data[$row->id] = $row;
}
$productResult = $db->query("SELECT id, brand_id, p_name FROM tbl_products");
while ($row = $productResult->fetchObject()) {
$data[$row->brand_id][$row->id] = $row->p_name;
}