使用对象元素中的数组属性的计数对数组进行排序

时间:2014-03-25 13:58:07

标签: php arrays sorting routes

我有一个对象数组@ routes,它包含我项目的所有Fs_Controller_Router_Route对象。

每个Fs_Controller_Router_Route对象都有controlleractionparams(数组),namealias属性。

可以使用get方法(getAction,getController,getParams,getName和getAlias)访问每个属性。

正如你在下面的数组中看到的那样,params属性是一个数组,包含当前路径的参数。

  array (size=6)
      'home' => 
        object(Fs_Controller_Router_Route)[3]
          private '_controller' => string 'index' (length=5)
          private '_action' => string 'index' (length=5)
          private '_params' => 
            array (size=2)
              ':name' => string 'Michael' (length=7)
              ':family_name' => string 'Corleone' (length=4)
          private '_name' => string 'home' (length=4)
          private '_alias' => string '/:name/:family_name' (length=19)
      'login' => 
        object(Fs_Controller_Router_Route)[4]
          private '_controller' => string 'index' (length=5)
          private '_action' => string 'login' (length=5)
          private '_params' => 
            array (size=0)
              empty
          private '_name' => string 'login' (length=5)
          private '_alias' => string '/login' (length=6)
      'signup' => 
        object(Fs_Controller_Router_Route)[5]
          private '_controller' => string 'index' (length=5)
          private '_action' => string 'signup' (length=6)
          private '_params' => 
            array (size=2)
              ':serial' => string 'dh3kddooo' (length=9)
              ':token' => string '304888030' (length=9)
          private '_name' => string 'signup' (length=6)
          private '_alias' => string '/signup/:token/:serial' (length=22)
      'about' => 
        object(Fs_Controller_Router_Route)[7]
          private '_controller' => string 'index' (length=5)
          private '_action' => string 'index' (length=5)
          private '_params' => 
            array (size=2)
              ':serial' => string 'dh3kddooo' (length=9)
              ':token' => string '304888030' (length=9)
          private '_name' => string 'about' (length=5)
          private '_alias' => string '/about/:serial/:token' (length=6)

我想要做的是使用每个对象的参数数量来升级对象。

我没有设法使用此代码。我根本不知道如何将count params部分添加到array_multisort函数

array_multisort(array_map('count', $routes), SORT_ASC, $routes);

1 个答案:

答案 0 :(得分:1)

感谢Andresch Serj的评论..我找到了解决方案,并且有效。

usort($routes, function($a,$b){

            if(count($b->getParams()) > count($a->getParams())){
                return 1;
            }else{
                return 0;
            }

        });

谢谢