data; //Making an array with all the emails and adding an extra property to $peopleArray foreach($peopleArray as $key => $peopleObj){ $emails[] = $peopleObj->email; $peopleObj->name = $peopleObj->first_name.' '.$peopleObj->last_name; } //Sorting $peopleArray by age in descending order. usort($peopleArray, function($prev,$next){ if ($prev->age === $next->age) { return 0; } return ($prev->age < $next->age) ? 1 : -1; }); $emails_list = implode($emails,','); //Converting array to comma saperated elements. $newData = json_encode(['data' => $peopleArray]); //Creating json using the mutated $peopleArray.