duanji9311 2012-04-15 07:20
浏览 52
已采纳

php数组排序包含的值

Ok, first of all, I'm not even sure the title is right, if so, I'm sorry.

I have this loop here which is the result of a MongoDB query:

foreach($cursor as $obj) {
   $monster = $obj["type"];
   $strenght = $obj["strenght"];
   $obj["value"] = rand(5, 15);
}

now, I have put rand there to signify that value changes for each iteration. Now i want that this array, when is printed, is ordered by that $obj["value"], and be able to chose if ascending or descending.


ok, I have tried this

foreach($cursor as $obj) {
   $type = $obj["monster"];
   $strenght = $obj["strenght"];
   $obj["value"] = rand(5, 15);

   $newarr[] = $obj;
}

    usort($newarr, "cmp");
    function cmp($a, $b)
    { return $b['value'] < $a['value']; }

    foreach ($newarr as $obj)
    {
        echo $obj['value'] . $obj['type'] . "<br/>";
    }

As I expected, the

 $obj["value"] = rand(5, 15);

does not get lost at every iteration in fact, the $newarr contains that value, the problem is that it does not sort them at all. The items are printed in the same order as they were put inside the array. Any help?

Thanks

  • 写回答

5条回答 默认 最新

  • dsegw3424 2012-04-15 07:25
    关注
    function mysort ($arr,$d='asc') { 
            global $dir; 
            $dir = $d; 
            uasort($arr, 'cmp'); 
            return ($arr); 
        } 
        function cmp ($a, $b) {
            global $dir;
            if($a['value'] == $b['value']) return 0;
            else  {
                if(strtolower($dir) == 'asc')
                    return ($a['value'] > $b['value']) ? 1 : -1;
                else if(strtolower($dir) == 'disc')
                    return ($a['value'] > $b['value']) ? -1 : 1;
    
            }
        } 
        print_r(mysort($obj, 'disc'));
    

    ACCORDING TO YOUR UPDATE

    try this cmp()

    function cmp($a, $b) {
        if($a['value'] == $b['value']) return 0;
        return $a['value'] > $b['value'] ? 1 : -1;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)