dongritan5654 2014-06-17 21: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 21:24
    关注

    Try this:

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

    See Demo

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

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法