I need to output the numbers by order of their sums.
<?php
$str = '11 11 2004 6 99 43 88 10003';
function orderWeight($str) {
$nums = explode(" ", $str);
$newArray= [];
foreach($nums as $key => $value){
$key = array_sum(str_split($value));
if(array_key_exists($key,$newArray)){
$key = $key + 0.5;
$newArray += array($key => $value);
}else{
$newArray += array($key => $value);
}
}
ksort($newArray);
$ans = implode(' ',$newArray);
print_r($ans);
}
echo(orderWeight($str));
The result is
11 10003 2004 43 88 99
It is sorted correctly but some numbers are overwritten by the keys that match by the sum.