【问题标题】:Sorting XML results with PHP usort + strcmp? (integers)使用 PHP usort + strcmp 对 XML 结果进行排序? (整数)
【发布时间】:2014-07-08 21:36:27
【问题描述】:

我试图通过比较 XML 对象中的一个字段的数值来排序我的页面上的 AJAX 调用的结果。基本上,这是一个产品人气排名,数字越高,越受欢迎。

我几乎可以正常工作,除了 strcmp 只比较第一个数字,所以目前的顺序是这样的:1、12、15、19、2、21、24、3、34、36、39, 5、52、56

如何修改此代码,以便无论有多少位,数字都按从低到高的顺序排列?

$products = array();
foreach($xml->Products as $product) {
    $products[] = $product;
};

// Sort results based on popularity
usort ($products, function($a, $b) {
    return strcmp($a->ProductPopularity, $b->ProductPopularity);
});

谢谢!

【问题讨论】:

    标签: php strcmp usort


    【解决方案1】:

    转换为整数并进行普通比较。

     usort($myArray, function($a, $b) {
          if((int)$a->ProductPopularity==(int)$b->ProductPopularity) return 0;
          return (int)$a->ProductPopularity < (int)$b->ProductPopularity?1:-1;
     });
    

    【讨论】:

      【解决方案2】:

      试试这个:

      usort ($products, function($a, $b) {
          return (int)($a->ProductPopularity) - (int)($b->ProductPopularity));
      });
      

      或者如果你想反转排序,你可以交换 a 和 b。

      【讨论】:

        【解决方案3】:
        $arr2 = array();
        foreach ($arr as $i => $row) {
            $arr2[$row['fieldname']] = $row;
        }
        ksort($arr2);
        $arr2 = array_values($arr2);
        

        【讨论】:

          猜你喜欢
          • 2018-03-26
          • 1970-01-01
          • 1970-01-01
          • 2023-03-31
          • 2012-01-29
          • 2011-01-18
          • 1970-01-01
          • 1970-01-01
          • 2011-09-19
          相关资源
          最近更新 更多