2012-03-30 47 views
0

我有一個類,它將值設置爲$ this->屬性在一個attach方法中。 我會在這裏縮短代碼簡單起見:如何按優先級排序此數組

<?php 
class Event 
{ 
    protected $properties = array(); 

    public function attach($event_name, $context, $event, $callback, $priority) 
    { 
     $this->properties [$event_name] = array(
       $context, 
       $event, 
       $callback, 
       $priority, 
     ); 
    } 

    public function dispatchAll($context = '0') 
    { 
     foreach($this->properties as $p) { 
      if($p[0] == $context) { 
       $this->dispatch($p[1]); 
      } else { 
       continue; 
      } 
     } 
    } 

    public function dispath($event_name) 
    { 
     // implentation not necessary for this question 
    } 
} 

我需要的是「背景下,優先」排序$this->properties,這樣我可以運行匹配我的應用程序在方興未艾爲了上下文的代碼。

婁僅有3組性質的var_dump

array(3) { 
    ["StartUp"]=> 
    array(4) { 
    [0]=> 
    string(1) "1" 
    [1]=> 
    string(7) "StartUp" 
    [2]=> 
    array(3) { 
     [0]=> 
     string(9) "Bootstrap" 
     [1]=> 
     string(7) "startup" 
     [2]=> 
     array(2) { 
     [0]=> 
     int(1) 
     [1]=> 
     object(Event)#6 (4) { 
      ["name":protected]=> 
      NULL 
      ["target":protected]=> 
      NULL 
      ["parameters":protected]=> 
      *RECURSION* 
      ["result":protected]=> 
      NULL 
     } 
     } 
    } 
    [3]=> 
    int(0) 
    } 
    ["View"]=> 
    array(4) { 
    [0]=> 
    string(1) "1" 
    [1]=> 
    string(4) "View" 
    [2]=> 
    array(2) { 
     [0]=> 
     string(9) "Bootstrap" 
     [1]=> 
     string(4) "view" 
    } 
    [3]=> 
    array(1) { 
     [0]=> 
     object(Event)#6 (4) { 
     ["name":protected]=> 
     NULL 
     ["target":protected]=> 
     NULL 
     ["parameters":protected]=> 
     *RECURSION* 
     ["result":protected]=> 
     NULL 
     } 
    } 
    } 
    ["ShutDown"]=> 
    array(4) { 
    [0]=> 
    string(1) "3" 
    [1]=> 
    string(8) "ShutDown" 
    [2]=> 
    array(2) { 
     [0]=> 
     string(9) "Bootstrap" 
     [1]=> 
     string(8) "shutdown" 
    } 
    [3]=> 
    array(1) { 
     [0]=> 
     object(Event)#6 (4) { 
     ["name":protected]=> 
     NULL 
     ["target":protected]=> 
     NULL 
     ["parameters":protected]=> 
     *RECURSION* 
     ["result":protected]=> 
     NULL 
     } 
    } 
    } 
} 
+1

你可以發佈'$ properties'的轉儲嗎? – F21 2012-03-30 06:02:43

+0

我已經將var_dump放在問題 – 2012-03-30 06:24:52

回答

0

usort()讓你排序用戶指定的功能的陣列。

或者,如果從數據庫填充數組,則可以始終在查詢中使用ORDER BY以按所需順序返回元素。

+0

的旁邊我已經嘗試使用usort()但沒有成功......實際上有很多其他變體。這就是爲什麼我發佈上述標題......'因爲他們是很多嘗試...我覺得我是一個新手...... hehehe – 2012-03-31 05:15:45