$stmnt = $pdo->prepare(" SELECT dog_id, dog_name, dog_sex, mother_id, father_id FROM tbl_dogs WHERE dog_id = ? "); fetchDogRecursive($yourDogId); function fetchDogRecursive($dogId) { $stmnt->execute(array($dogId)); $dogData = $stmnt->fetchAll(PDO::FETCH_ASSOC)[0]; $dog = array( 'id' => $dogData['dog_id'], 'name' => $dogData['dog_name'], 'mother' => null, 'father' => null ); if($dogData['mother_id'] !== null) { $dog['mother'] = fetchDogRecursive($dogData['mother_id']); } if($dogData['father_id'] !== null) { $dog['father'] = fetchDogRecursive($dogData['father_id']); } return $dog; }