使用usort对JSON字符串进行排序 - 仅排序前两个对象

时间:2014-05-13 02:11:10

标签: php arrays json sorting

我的JSON字符串,

enter image description here

$rs是我的阵列, 我正在做,

while($ra[] = mysql_fetch_assoc($dno)) 
    {
        $restaurants['id']=$ra[$counter]['R_ID'];
        $restaurants['name']=$ra[$counter]['name'];

        $distancefull = distance($userlat, $userlon, $ra[$counter]['lat'], $ra[$counter]['lng'], "K");
        $restaurants['distance'] = (float)round($distancefull, 2);   

        $restaurants['contact']=$ra[$counter]['contact'];
        $restaurants['area']=$ra[$counter]['area'];
    $counter++;
    $rs[]=$restaurants;
    }
    function cmp($a, $b)
    {
        //return strcmp($a["distance"], $b["distance"]);
        return ($a["distance"] - $b["distance"]);
    }

    usort($rs, "cmp");

 return $rs;

然后,

json_encode(array('Reataurants'=>$rs),JSON_NUMERIC_CHECK);

我想按距离对对象进行排序,但只完成了前两个。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

距离看起来像浮动而不是字符串。做:

function cmp($a, $b) {
    return $a["distance"] - $b["distance"];
}
相关问题