dongritan5654 2014-06-17 13:06
浏览 44
已采纳

按特定键值排序关联数组

I have the following array:

   $data=array(
   'Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']
    );

This resides in a for each loop in my Codeigniter controller index function:

public function index(){

    $query=$this->My_model->get_data();
    foreach ($query as $row)
    {
           $data=array(
           'Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']
            );

    }
}

Currently if I print_r on $data it would produce:

Array ( [Points] => 500 [Name] => Dave Laus ) 
Array ( [Points] => 1200 [Name] => John Smith ) 
Array ( [Points] => 700 [Name] => Jason Smithsonian ) 

However I would like to sort/order this so that the user with the highest points showing first like this:

Array ( [Points] => 1200 [Name] => John Smith ) 
Array ( [Points] => 700 [Name] => Jason Smithsonian ) 
Array ( [Points] => 500 [Name] => Dave Laus ) 

I want to sort the array by the "Points" key, so that the user with the highest points appear first. I want to re order the array to show from highest to lowest points.

I have tried usort and arsort and ksort. I haven't gotten it to work.

How do I do this?

I tried this in my controller, but it's doesn't work, errors instead:

public function index(){

    $query=$this->My_model->get_data();
    foreach ($query as $row)
    {
           $data=array(
           array('Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']),
            );

           function cmp ($a, $b) {
        return $a['Points'] < $b['Points'] ? 1 : -1;
        }

        usort($data, "cmp");

            print_r($data);


                //I also tried usort($leaders, array('home', 'cmp')); whcih gave no errors, but was the same result as before, not ordered


        }
    }

展开全部

  • 写回答

3条回答 默认 最新

  • douhuang7263 2014-06-17 13:24
    关注

    Try this:

    function cmp ($a, $b) {
        return $a['Points'] < $b['Points'] ? 1 : -1;
    }
    
    usort($data, "cmp");
    

    See Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部