2012-09-22 43 views
0
foreach ($this->parent->get_sections(null, $this->parent->author) as $section) 
{ 
    //... 
} 

我想要做的是強制循環輸出每個$section我想要的順序。每個$section的名字可以通過$section->name檢索。假設我想首先輸出$section「Section 2」,然後輸出「Section 1」(而不是按照foreach的順序輸出)。我怎麼能強迫它做到這一點?我認爲正確的方法將是一個for循環與每次檢查部分名稱。轉換foreach到在PHP中

回答

1

不知道你的代碼的結構,我會做類似的事情。

// Get Org Sections 
$sections = $this->parent->get_sections(null, $this->parent->author); 

// Loop thru sections to get an array of names 
foreach ($sections as $key=>$section) 
{ 
$sorted_sections[$section->name] = $key; 
} 

// Sort Array 
//ksort — Sort an array by key 
//krsort — Sort an array by key in reverse order 
krsort($sorted_sections); 

foreach ($sorted_sections as $section) 
{ 
// Orig Code 
} 
1
$section = $this->parent->get_sections(null, $this->parent->author); 
    echo $section[2]->name; 
    echo $section[1]->name;//just output the indexes the way you want 

,如果你需要它有序,在說降序排列,您可以排序它的方式,然後使用for循環顯示。

+0

感謝您的信息! – globetrotter

4

當您撥打parent->get_sections()時,正確的方法是對結果進行排序。你如何做到這一點完全取決於該類和方法的實現。爲了排序,將此foreach更改爲for對我來說似乎是一種代碼味道。


爲了儘量回答問題。

$sections = $this->parent->get_sections(null, $this->parent->author); 
$num_sections = count($sections); 
for ($i = 0; $i < $num_sections; $i++) { 
    // what you do here is up to you $sections[$i] 
} 
+0

謝謝,我知道它看起來像一個代碼氣味,但不幸的是插件是粗略的,我需要一個快速的修復。 – globetrotter

2

特別是如果你不知道段的具體數量,你可以使用usort()get_sections() -returned數組或對象的動態自定義排序,然後利用現有的代碼。 (這比在for/foreach循環中做同樣的事情要更優雅一點,imo)。

+0

會檢查出來,謝謝! – globetrotter