【问题标题】:Sorting JSON string with usort - only sorting 1st two objects使用 usort 对 JSON 字符串进行排序 - 仅对第一个两个对象进行排序
【发布时间】:2014-05-13 02:11:09
【问题描述】:

我的 JSON 字符串,

$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);

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

感谢您的帮助。

【问题讨论】:

  • $rs 是直接从json_decode() 得到的结果吗?或者您是否将$rs 设置为json_decode() 调用返回的对象的Restaurants 属性处的数组?换句话说,你做了$rs = json_decode($json); 还是$json_object = json_decode($json); $rs = $json_object->Restaurants;
  • json_encode(array('Reataurants'=>$rs),JSON_NUMERIC_CHECK);
  • 这毫无意义。您需要解码 JSON 才能使用它。
  • usort之前的$rs是什么,之后是什么?
  • 我想在 json_encode 之前对数组进行排序,所以可能不需要解码,请参阅评论问题。我添加了更多细节。

标签: php arrays json sorting


【解决方案1】:

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

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

【讨论】:

  • 谢谢,b-a 给出了 desc 顺序,a-b 给出了 asc,但仍然没有正确排序。 8.52、8.3、7.97、11.33、11.39 未完全排序。
  • 也许它们不是浮点数而是字符串。所以试试:(float)$a["distance"] - (float)$b["distance"]
  • 它们基本上是字符串,我使用 JSON_NUMERIC_CHECK... 在 (float)@a... 之后仍然相同...
  • 如果您在每个距离上执行(float)$a["distance"] 并打印它们。你得到了什么?
  • 然后我想你做错了什么。你能发布更多代码吗?
猜你喜欢
  • 2012-03-04
  • 2022-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
  • 1970-01-01
  • 2012-01-29
相关资源
最近更新 更多