2012-09-22 41 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