After calling your recursive array you need finish up with a single array - you output a separate array during each iteration.
Don't connect to db inside functions - it's the slowest part of the process and inefficient (plus you can quickly reach your connctions limit). Connect once then pass the connection to the functions.
Don't include the separator in you results - add that when you implode (join).
(Sorry for any delay - it's not easy to load an image of data into a database test table)
My method...
function retrieve_category_path($pdo, $id, &$cpa){
// DB connection
// Company ID
$stmt = $pdo->prepare("SELECT CONCAT(name, '::', position) as name
, parent
FROM category WHERE id = ?
");
$stmt->execute([$id]);
while($row=$stmt->fetch()){
$parent =$row['parent'];
$name = $row['name'];
$cpa[] = $row['name']; // append into array
if($row['parent'] > 0){
retrieve_category_path($pdo, $row['parent'], $cpa);
}
}
}
$category_path_array = [];
retrieve_category_path($pdo, 552, $category_path_array);
$breadcrumbs = join('/', array_reverse($category_path_array));
echo $breadcrumbs; // Cars::2/Sports cars::1/Petrol::1/2 Door::0