2011-05-03 91 views
1

我有一個從自定義Joomla內的SQL查詢生成的對象數組! 1.5組件:PHP根據另一個數組的內容對對象數組重新排序

$query = 'SELECT * FROM #__orders_hearaboutus ORDER BY id'; 
$this->_hearaboutus = $this->_getList($query); 

這會產生這樣的:

Array 
(
    [0] => stdClass Object 
     (
      [id] => 3 
      [how_heard] => Our Website 
     ) 

    [1] => stdClass Object 
     (
      [id] => 4 
      [how_heard] => Other Website 
     ) 

    [2] => stdClass Object 
     (
      [id] => 5 
      [how_heard] => Word of Mouth 
     ) 

    [3] => stdClass Object 
     (
      [id] => 6 
      [how_heard] => Other 
     ) 

    [4] => stdClass Object 
     (
      [id] => 10 
      [how_heard] => Internet Search Engine 
     ) 

    [5] => stdClass Object 
     (
      [id] => 11 
      [how_heard] => Local Newspaper 
     ) 

    [10] => stdClass Object 
     (
      [id] => 16 
      [how_heard] => Leaflet by Post 
     ) 

    [11] => stdClass Object 
     (
      [id] => 18 
      [how_heard] => Club or Society Newsletter 
     ) 

) 

然後,這是產生「你從哪裏知道我們的」一個訂單內的下拉選項的HTML選擇。

我希望做的是通過在所需的(任意)順序提供的ID進行重新排序列表,假設數組是做到這一點的最好辦法:

$ordering = array(11,3,4,10,16,5,18,6); 

我已經找到了以這種方式重新排序數組的方法,或者通過鍵重新排序對象的數組,但是我無法弄清楚如何實現上述目標?

回答

0

你可以在MySQL做到這一點像@deceze提到或PHP,使用array_multisort()

array_multisort($this->_hearaboutus, $ordering, SORT_ASC); 
0

由@deceze提到通過的MySQL這樣做很可能是做的最好的辦法,但這裏有一個快速的和骯髒的方式來實現你所需要的。

class testObj { 
    public $id; 
    function __construct($id) { 
     $this->id = $id; 
    } 
} 

$order = array(11, 3, 4, 10, 16, 5, 18, 6); 
$objects = array(
    new testObj(3), 
    new testObj(4), 
    new testObj(5), 
    new testObj(6), 
    new testObj(10), 
    new testObj(11), 
    new testObj(16), 
    new testObj(18) 
); 

$neworder = array(); 

foreach ($order as $ord) { 

    foreach ($objects as $obj) { 

     if ($obj->id == $ord) { 
      $neworder[] = $ord; 
     } 

    } 

} 

print_r($neworder); 
相關問題