Нет необходимости отслеживать предыдущие элементы и тому подобное, просто используйте идентификатор в качестве ключа массива, чтобы вы могли проверить, существует ли он.Если вы не хотите, чтобы это было в вашем конечном выводе, используйте array_values()
для удаления ключей:
<?php
$results = [
["business_id" => 1, "business_name" => "ABC", "business_branch" => 1, "branch_contact" => "1111111111"],
["business_id" => 1, "business_name" => "ABC", "business_branch" => 2, "branch_contact" => "2222222222"],
["business_id" => 1, "business_name" => "ABC", "business_branch" => 3, "branch_contact" => "3333333333"],
["business_id" => 1, "business_name" => "ABC", "business_branch" => 4, "branch_contact" => "4444444444"],
["business_id" => 2, "business_name" => "XYZ", "business_branch" => 1, "branch_contact" => "5555555555"],
["business_id" => 2, "business_name" => "XYZ", "business_branch" => 2, "branch_contact" => "6666666666"],
];
$output = [];
foreach ($results as $result) {
if (empty($output[$result["business_id"]])) {
$output[$result["business_id"]] = [
"business_id" => $result["business_id"],
"business_name" => $result["business_name"],
"branches" => [],
];
}
$output[$result["business_id"]]["branches"][] = [
"branch_id" => $result["business_branch"],
"branch_contact" => $result["branch_contact"],
];
}
echo json_encode(array_values($output), true);
Вывод:
[{"business_id":1,"business_name":"ABC","branches":[{"branch_id":1,"branch_contact":"1111111111"},{"branch_id":2,"branch_contact":"2222222222"},{"branch_id":3,"branch_contact":"3333333333"},{"branch_id":4,"branch_contact":"4444444444"}]},{"business_id":2,"business_name":"XYZ","branches":[{"branch_id":1,"branch_contact":"5555555555"},{"branch_id":2,"branch_contact":"6666666666"}]}]