Isn't it easier to encode $result[$id] = $name? Then you don't need the for()-loop in Javascript to get all names